2018-02-20 00:20:21 +00:00
|
|
|
# Native File Drag & Drop
|
|
|
|
|
2020-10-16 02:14:16 +00:00
|
|
|
## Overview
|
|
|
|
|
2018-02-20 00:20:21 +00:00
|
|
|
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.
|
|
|
|
|
2020-10-16 02:14:16 +00:00
|
|
|
To implement this feature in your app, you need to call the
|
|
|
|
[`webContents.startDrag(item)`](../api/web-contents.md#contentsstartdragitem)
|
2018-02-20 00:20:21 +00:00
|
|
|
API in response to the `ondragstart` event.
|
|
|
|
|
2020-10-16 02:14:16 +00:00
|
|
|
## Example
|
|
|
|
|
|
|
|
Starting with a working application from the
|
|
|
|
[Quick Start Guide](quick-start.md), add the following lines to the
|
|
|
|
`index.html` file:
|
2018-02-20 00:20:21 +00:00
|
|
|
|
|
|
|
```html
|
2020-10-16 02:14:16 +00:00
|
|
|
<a href="#" id="drag">Drag me</a>
|
|
|
|
<script src="renderer.js"></script>
|
2018-02-20 00:20:21 +00:00
|
|
|
```
|
|
|
|
|
2020-10-16 02:14:16 +00:00
|
|
|
and add the following lines to the `renderer.js` file:
|
|
|
|
|
2020-11-30 07:48:39 +00:00
|
|
|
```javascript
|
2020-10-16 02:14:16 +00:00
|
|
|
const { ipcRenderer } = require('electron')
|
|
|
|
|
|
|
|
document.getElementById('drag').ondragstart = (event) => {
|
|
|
|
event.preventDefault()
|
|
|
|
ipcRenderer.send('ondragstart', '/absolute/path/to/the/item')
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
The code above instructs the Renderer process to handle the `ondragstart` event
|
|
|
|
and forward the information to the Main process.
|
|
|
|
|
|
|
|
In the Main process(`main.js` file), expand the received event with a path to the file that is
|
|
|
|
being dragged and an icon:
|
2018-02-20 00:20:21 +00:00
|
|
|
|
2020-11-30 07:48:39 +00:00
|
|
|
```javascript fiddle='docs/fiddles/features/drag-and-drop'
|
2018-02-20 00:20:21 +00:00
|
|
|
const { ipcMain } = require('electron')
|
|
|
|
|
|
|
|
ipcMain.on('ondragstart', (event, filePath) => {
|
|
|
|
event.sender.startDrag({
|
|
|
|
file: filePath,
|
|
|
|
icon: '/path/to/icon.png'
|
|
|
|
})
|
|
|
|
})
|
|
|
|
```
|
2020-10-16 02:14:16 +00:00
|
|
|
|
2020-10-19 21:18:43 +00:00
|
|
|
After launching the Electron application, try dragging and dropping
|
2021-01-20 19:28:10 +00:00
|
|
|
the item from the BrowserWindow onto your desktop. In this guide,
|
2020-10-16 02:14:16 +00:00
|
|
|
the item is a Markdown file located in the root of the project:
|
|
|
|
|
|
|
|
![Drag and drop](../images/drag-and-drop.gif)
|