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.

  • Project Structure:
    Project Structure

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

  • Step 1: Navigate to an Empty Directory to setup the project, and run the following command,
    npm init

    To generate the package.json file. Install Electron using npm if it is not installed.



    npm install electron --save

    This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Create the assets folder according to the project structure. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file. This image file will be dragged-and-dropped onto the BrowserWindow of the Electron application.
    package.json:

    {
      "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"
      }
    }
    
  • Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.

    main.js:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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.

    chevron_right

    
    

  • Step 3: Create the index.html file and index.js file within the src directory according to project structure. We will also copy the Boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.

    index.html:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!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>

    chevron_right

    
    

  • Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:
    npm start

    GUI Output

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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');
});

chevron_right


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.

  • event.dataTransfer This Instance Property is used to represent the data that is being transferred during a Drag and Drop Operation. In our case, the data being transferred is a file and hence we have used event.dataTransfer.files and fetched the absolute file path using the path attribute provided by Electron. We can also drag and drop multiple files at once. In case of the data being a text selection, we can simply use event.dataTransfer.setData(key, text) method when initiating a Drag operation. This method sets a unique key for the text data being transferred. To retrieve the text selection on the Drop Operation, we can simply use event.dataTransfer.getData(key) method. This method will return any data which was set using the unique key provided.
  • dragover: Event This event is fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds) such as another DOM element. The firing pattern for this event depends on the movement of the mouse pointer. By default, this event fires every 50 ms when the mouse pointer is not moving over a valid drop target else much faster between 5 ms and 1 ms approximately but this behaviour varies. The Event Handler Property for this event is ondragover. By default, a element or a text selection cannot be dropped in other DOM elements. To allow a drop, we must prevent the default handling of the element. Hence we have used the event.preventDefault() method for this very purpose. The default handling of an element is open as link in the browser on drop.
  • drop: Event This event is fired when an element or text selection is dropped on a valid drop target such as another DOM element. The Event Handler Property for this event is ondrop. We need to prevent the default handling of the element in this Event also as done for the dragover Event.
  • dragenter: Event This event is fired when a dragged element or text selection enters a valid drop target such as another DOM element. The Event Handler Property for this event is ondrageneter.
  • dragleave: Event This event is fired when a dragged element or text selection leaves a valid drop target such as another DOM element. The Event Handler Property for this event is ondragleave.

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. Propogation means transferring up to the Parent DOM elements or transferring down to the Child DOM elements.

Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.