Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag html element outside electron window to copy local file?

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.

like image 601
Pwdr Avatar asked Feb 07 '23 03:02

Pwdr


2 Answers

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

like image 161
Pwdr Avatar answered Feb 08 '23 15:02

Pwdr


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',
});
like image 27
MarshallOfSound Avatar answered Feb 08 '23 17:02

MarshallOfSound