Does Electron support drag-and-dropping a file path into another application?

Viewed 85

In C# WinForms, I could do this

var data = new DataObject(DataFormats.FileDrop, filePaths);
myControl.DoDragDrop(data, DragDropEffects.Copy);

to make another application, such as Notepad, open the file specified by filePaths. The code is similar in WPF or even in JavaFX. The file path can be any arbitrary file path that is accessible within the system, such as C:\Windows\win.ini or \\myFileServer\sharedDir\sharedFile.txt. I mean making Notepad OPEN the file, NOT displaying the file path text in its editing area. That is, I am d&d'ing a file path, not a string that contains the file path.

Can I do the same thing if I make a desktop application with Electron (only for desktops; don't care about web/mobile)? I have tested it with VS Code, which is said to be created with Electron, and when I dragged a file from its "Explorer" into Notepad, nothing happened. When I did it into Notepad++, it just displayed the file path string in its editing area, so I am guessing Electron doesn't support it, but I want to make it sure.

1 Answers

Yes, there even is a full example in the Electron documentation about this.


Short summary of the example code: when a specific DOM element is being dragged, the renderer sends an event to the main process. For the dragstart event to fire, the DOM element needs to have the attribute draggable="true". In this example, we pass the filename of the file to be dragged along in the message to the main process.

document.getElementById("foo").ondragstart = event => {
    event.preventDefault();
    ipcRenderer.send("my-drag-start", "test-file.txt");
}

The main process handles the IPC message from the renderer and starts the drag operation. Note that you need to specify an icon to be attached to the cursor during the drag operation, triggering an error message if left out.

ipcMain.on("my-drag-start", (event, filePath) => {
    event.sender.startDrag({
        file: path.join(__dirname, filePath),
        icon: path.join(__dirname, "dnd.png"),
    });
});
Related