最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Drag html element outside electron window to copy local file? - Stack Overflow

programmeradmin1浏览0评论

I am planning to realize a music player with electron. It will list music from the user’s hard drive.
Is it possible to define a drag’n’drop behavior so that I can drag a html element, e.g. <span>Artist – Title</span> outside the electron window onto the user’s desktop to copy the actual file?

File is stored here: ~/music/Artist-Title.mp3.

When drag’n’dropping the spanfrom my electron window onto the desktop a copy should be made: ~/Desktop/Artist-Title.mp3.

I am planning to realize a music player with electron. It will list music from the user’s hard drive.
Is it possible to define a drag’n’drop behavior so that I can drag a html element, e.g. <span>Artist – Title</span> outside the electron window onto the user’s desktop to copy the actual file?

File is stored here: ~/music/Artist-Title.mp3.

When drag’n’dropping the spanfrom my electron window onto the desktop a copy should be made: ~/Desktop/Artist-Title.mp3.

Share Improve this question asked Sep 15, 2016 at 8:14 PwdrPwdr 3,7914 gold badges31 silver badges39 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Working example:

Put into main.js and copy an icon to be shown while dragging (yourAppDir/img/icon/folder.png):

const {ipcMain} = require('electron')

ipcMain.on('ondragstart', (event, filePath) => {
  event.sender.startDrag({
    file: filePath,
    icon: 'img/icon/folder.png'
  })
})

Put into renderer.js, and set the path to the file you want to drop out:

var ipcRenderer = require('electron').ipcRenderer

document.getElementById('drag').ondragstart = (event) => {
    event.preventDefault()
    ipcRenderer.send('ondragstart', '/Users/tim/dev/test/elektron-drag-out-test/img/icon/folder.png')
  }

Create the draggable element inside the body tags of index.html:

...
<body>
  ...
  <a href="#" id="drag" class="draggable">drag item</a>
</body>
...

I also created a gist for drag in / out.

Another helpful resource: Electron – Add webContents.startDrag(item) API

I believe this is the API you are looking for.

http://electron.atom.io/docs/api/web-contents/#contentsstartdragitem

remote.getCurrentWebContents().startDrag({
  file: 'path/to/file',
  icon: 'path/to/file/icon',
});
发布评论

评论列表(0)

  1. 暂无评论