Saltar al contenido principal

Función nativa de Arrastrar y Soltar archivo

Descripción general

Ciertos tipos de aplicaciones que manipulan archivos podrían querer soportar la función nativa de arrastrar & soltar archivos del sistema operativo. Arrastrar archivos dentro de un web content es común y soportado por muchos sitios web. Adicionalmente Electron soporta arrastre de archivos fuera del web content dentro del mundo del sistema.

To implement this feature in your app, you need to call the webContents.startDrag(item) API in response to the ondragstart event.


An example demonstrating how you can create a file on the fly to be dragged out of the window.


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')
const path = require('node:path')

contextBridge.exposeInMainWorld('electron', {
startDrag: (fileName) => {
ipcRenderer.send('ondragstart', path.join(process.cwd(), fileName))


Add a draggable element to index.html, and reference your renderer script:

<div style="border:2px solid black;border-radius:3px;padding:5px;display:inline-block" draggable="true" id="drag">Drag me</div>
<script src="renderer.js"></script>


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) => {


In the Main process (main.js file), expand the received event with a path to the file that is being dragged and an icon:

const { app, BrowserWindow, ipcMain } = require('electron/main')
const path = require('node:path')
const fs = require('node:fs')
const https = require('node:https')

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')


const iconName = path.join(__dirname, 'iconForDragAndDrop.png')
const icon = fs.createWriteStream(iconName)

// Create a new file to copy - you can also copy existing files.
fs.writeFileSync(path.join(__dirname, ''), '# First file to test drag and drop')
fs.writeFileSync(path.join(__dirname, ''), '# Second file to test drag and drop')

https.get('', (response) => {


ipcMain.on('ondragstart', (event, filePath) => {
file: path.join(__dirname, filePath),
icon: iconName

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {

Después de lanzar la aplicación Electron, intente arrastrar y soltar el elemento desde el BrowserWindow a su escritorio. In this guide, the item is a Markdown file located in the root of the project:

Arrastrar y soltar