Open In App

Drag and Drop Files in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
There are several differences between a Drag-and-Drop Operation in traditional web applications and Electron. One of the major differences is that Electron applications work with the native filesystem in the OS environment. Hence we need to obtain the absolute file path for any files dragged onto the Electron application from the native file dialog on the user’s machine. Once we have obtained the file path, we can perform file operations using the NodeJS fs module or upload the file to a server. Electron makes use of the HTML5 File API to work with files in the native filesystem. This tutorial will demonstrate how to implement Drag-and-Drop functionality for native files in an Electron application.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
 



Example: We will start by building the basic Electron Application by following the given steps. 

npm init
npm install electron --save
{
  "name": "electron-drag",
  "version": "1.0.0",
  "description": "File Drag and Drop in Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [
    "electron"
  ],
  "author": "Radhesh Khanna",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.3.0"
  }
}




const { app, BrowserWindow } = require('electron')
 
function createWindow () {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
 
  // Load the index.html of the app.
  win.loadFile('src/index.html')
 
  // Open the DevTools.
  win.webContents.openDevTools()
}
 
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
// This method is equivalent to 'app.on('ready', function())'
app.whenReady().then(createWindow)
 
// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
 
app.on('activate', () => {
    // On macOS it's common to re-create a window in the
    // app when the dock icon is clicked and there are no
    // other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
 
// In this file, you can include the rest of your
// app's specific main process code. You can also
// put them in separate files and require them here.




<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
                           /security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy"
          content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node
    <script>
        document.write(process.versions.node)
    </script>, Chrome
    <script>
        document.write(process.versions.chrome)
    </script>, and Electron
    <script>
        document.write(process.versions.electron)
    </script>.
 
    <br><br>
    <h3>Drag and Drop Files in the Window.</h3>
 
    <!-- Adding Individual Renderer Process JS File -->
    <script src="index.js"></script>
  </body>
</html>

npm start



Using the HTML5 File API, users can directly work with the native files in the system OS environment. This is possible because the DOM’s File Interface provides an abstraction for the underlying native filesystem. Electron enhances the DOM’s File Interface by adding a path attribute to it. This path attribute exposes the absolute file path of the files on the filesystem. We will be making use of this functionality to get the absolute file path of a dragged-and-dropped file onto the Electron application. For more detailed Information, Refer this link.
All the Instance events of the Drag-and-Drop Operation belong to the DragEvent Interface. This event is a DOM Event that represents a drag-and-drop operation from start to finish. This Interface also inherits properties from the MouseEvent and the global Event Interface. It has specific Instance Properties for data transfer, GlobalEventHandlers and Instance Events which we have used in our code. For more detailed Information, Refer this link.
index.js: Add the following snippet in that file. 




document.addEventListener('drop', (event) => {
    event.preventDefault();
    event.stopPropagation();
 
    for (const f of event.dataTransfer.files) {
        // Using the path attribute to get absolute file path
        console.log('File Path of dragged files: ', f.path)
      }
});
 
document.addEventListener('dragover', (e) => {
    e.preventDefault();
    e.stopPropagation();
  });
 
document.addEventListener('dragenter', (event) => {
    console.log('File is in the Drop Space');
});
 
document.addEventListener('dragleave', (event) => {
    console.log('File has left the Drop Space');
});

A Detailed explanation of all the Instance Events and Properties of the HTML5 File API used in the code are explained below. All the Instance Events of DragEvent Interface will be fired upon the global document object and cannot be directly fired on a Specific DOM element. 

The dragStart, drag, dragend and dragexit Instance events will not be fired in this particular code example and hence have been excluded from the same. All of these Instance Events are fired on the Drag Target and in this case, drag Target does not exist in the application. The Drag Operation for files is initiated from outside the application from within the native filesystem dialog. All of the Instance events used in the above code are triggered on the Drop Target which lies within the application. 
Note: The event.stopPropagation() method prevents propagation of the same event from being called. Propagation means transferring up to the Parent DOM elements or transferring down to the Child DOM elements.
Output: 


Article Tags :