Native File Drag & Drop
Overview
Certain kinds of applications that manipulate files might want to support the operating system's native file drag & drop feature. Dragging files into web content is common and supported by many websites. Electron additionally supports dragging files and content out from web content into the operating system's world.
To implement this feature in your app, you need to call the
webContents.startDrag(item)
API in response to the ondragstart event.
Example
An example demonstrating how you can create a file on the fly to be dragged out of the window.
Preload.js
In preload.js use the contextBridge to inject a method window.electron.startDrag(...) that will send an IPC message to the main process.
const{ contextBridge, ipcRenderer }=require('electron')
contextBridge.exposeInMainWorld('electron',{
startDrag:(fileName)=> ipcRenderer.send('ondragstart', fileName)
})
Index.html
Add a draggable element to index.html, and reference your renderer script:
<divstyle="border:2px solid black;border-radius:3px;padding:5px;display:inline-block"draggable="true"id="drag">Drag me</div>
<scriptsrc="renderer.js"></script>
Renderer.js
In renderer.js set up the renderer process to handle drag events by calling the method you added via the contextBridge above.
document.getElementById('drag').ondragstart=(event)=>{
event.preventDefault()
window.electron.startDrag('drag-and-drop.md')
}
Main.js
In the Main process (main.js file), expand the received event with a path to the file that is
being dragged and an icon:
<title>Hello World!</title>
<metahttp-equiv="Content-Security-Policy"content="script-src 'self' 'unsafe-inline';"/>
</head>
<body>
<h1>Hello World!</h1>
<p>Drag the boxes below to somewhere in your OS (Finder/Explorer, Desktop, etc.) to copy an example markdown file.</p>
<divstyle="border:2px solid black;border-radius:3px;padding:5px;display:inline-block"draggable="true"id="drag1">Drag me - File 1</div>
<divstyle="border:2px solid black;border-radius:3px;padding:5px;display:inline-block"draggable="true"id="drag2">Drag me - File 2</div>
<scriptsrc="renderer.js"></script>
</body>
</html>
document.getElementById('drag1').ondragstart=(event)=>{
event.preventDefault()
window.electron.startDrag('drag-and-drop-1.md')
}
document.getElementById('drag2').ondragstart=(event)=>{
event.preventDefault()
window.electron.startDrag('drag-and-drop-2.md')
}