Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Native APIs and Files

Drag and Drop, File Associations and Deep Links

Accept dropped files, start native drags out of your window, handle double-clicked documents and myapp:// deep links, and keep a single running instance in Electron.

Users expect a desktop app to be woven into the system. They drag a picture onto its window, double-click a .note file in the file manager, or click a myapp://invite/42 link in an email and expect the right window to appear. Each of these arrives in your app in a slightly different way, and several of them behave differently on macOS, Windows and Linux.

This lesson covers four entry points: files dropped into a window, files dragged out of your window, files opened through the OS, and custom protocol links. It ends with single instance lock, the piece that makes the last two behave sensibly when the app is already running.

Dropping files into a window

Inside a renderer, drag and drop is the standard HTML API. The special part is what you get from a dropped file: in modern Electron the File object no longer exposes a path. Use webUtils.getPathForFile from the preload script.

JavaScript
// preload.js
import { contextBridge, webUtils } from 'electron';

contextBridge.exposeInMainWorld('drop', {
  pathFor: (file) => webUtils.getPathForFile(file),
});
HTML
<div id="zone">Drop files here</div>
<script>
  const zone = document.getElementById('zone');
  zone.addEventListener('dragover', (e) => e.preventDefault());
  zone.addEventListener('drop', (e) => {
    e.preventDefault();
    const paths = [...e.dataTransfer.files].map((f) => window.drop.pathFor(f));
    window.api.importFiles(paths);   // send to the main process
  });
</script>

Calling preventDefault() on dragover is required or the browser will not allow a drop. Calling it on drop stops Chromium from navigating the window to the file, which is what happens by default and wipes out your app.

A dropped path is untrusted input. The main process must validate it as covered in Validating IPC and Handling Secrets: check that it is a string, resolve it, and check the extension and size before reading.

Deciding what to accept

Dropped items can be anything: images, folders, 4 GB videos. A small classifier belongs between the drop and the real work. The next example runs the kind of check you would put in a main-process handler, on plain data.

Node.js Classifying dropped files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Dragging files out

Sometimes the user should be able to grab something from your window and drop it in the file manager or an email: an exported image, a generated PDF. The renderer starts the drag with dragstart, and the main process answers with webContents.startDrag.

JavaScript
// main.js
ipcMain.on('drag-out', (event, fileName) => {
  const file = join(app.getPath('temp'), fileName);       // already written to disk
  event.sender.startDrag({ file, icon: nativeImage.createFromPath('drag.png') });
});
JavaScript
// renderer
el.addEventListener('dragstart', (e) => {
  e.preventDefault();
  window.api.startDrag('export.png');
});

The file must exist on disk before the drag starts, so write it first. Generate the temp file from a known name rather than a path supplied by the renderer.

Files opened by the operating system

When a user double-clicks report.note and your app is registered for that extension, the OS launches your app (or notifies the running instance) with the path. How you receive it differs:

  • Windows and Linux: the path is in process.argv of a new process.
  • macOS: the open-file event on app, which can fire before ready.
JavaScript
let pendingFile = null;

app.on('open-file', (event, path) => {      // macOS
  event.preventDefault();
  pendingFile = path;
  if (app.isReady()) openDocument(path);
});

app.whenReady().then(() => {
  const fromArgs = process.argv.find((a) => a.endsWith('.note'));   // Windows, Linux
  openDocument(pendingFile ?? fromArgs);
});

The extension itself is registered by your installer (see Installers and Code Signing), not at runtime.

A deep link is a URL with your own scheme, such as notes://open?id=42. Register your app as the handler:

JavaScript
if (process.defaultApp) {
  app.setAsDefaultProtocolClient('notes', process.execPath, [path.resolve(process.argv[1])]);
} else {
  app.setAsDefaultProtocolClient('notes');
}

Then receive it: open-url on macOS, and process.argv (or the second-instance event) on Windows and Linux. Deep links are input from the outside world, so parse them strictly and treat every part as untrusted.

Node.js Parsing a deep link safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The action table is checked with Object.hasOwn, so notes://constructor cannot reach inherited properties, and nothing in a link can run code or name a path.

One instance only

Without a lock, every click on a deep link or document starts a second copy of your app. The fix is requestSingleInstanceLock:

JavaScript
if (!app.requestSingleInstanceLock()) {
  app.quit();
} else {
  app.on('second-instance', (_event, argv) => {
    if (mainWindow?.isMinimized()) mainWindow.restore();
    mainWindow?.focus();
    const link = argv.find((a) => a.startsWith('notes://'));
    if (link) handleDeepLink(link);
  });
}

The first instance keeps the lock and receives second-instance with the arguments of the newcomer, which quits immediately.

flowchart LR
  A["User clicks notes://open?id=42"] --> B{"Instance already running?"}
  B -- no --> C["Start app, handle argv"]
  B -- yes --> D["New process quits"]
  D --> E["Running app gets second-instance event"]
  E --> F["Focus window, handle link"]

The lock turns every later launch into a message to the first one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must a drop handler call preventDefault on the drop event?

    By default Chromium opens a dropped file in the window, replacing your app UI. preventDefault keeps your page in place so your code can handle the file.
  2. 2. How does a sandboxed renderer obtain the real path of a dropped File?

    File.path was removed. The preload script calls webUtils.getPathForFile and exposes a narrow wrapper.
  3. 3. On macOS, which event delivers a double-clicked document?

    macOS sends open-file to the app, possibly before ready. Windows and Linux pass the path on the command line.
  4. 4. What does requestSingleInstanceLock achieve?

    Only one process holds the lock. Others get false, quit, and their arguments arrive in the first process via the second-instance event.

Summary

  • Dropped files come through standard DOM events; get paths with webUtils.getPathForFile and validate them in the main process.
  • webContents.startDrag drags a file that already exists out of the window.
  • Documents arrive via open-file on macOS and argv elsewhere; protocol links via open-url or argv.
  • Parse deep links like any external input: allowlist the scheme and actions, check every parameter.
  • Use the single instance lock so links and documents reach the running app.

Next: The Electron Security Checklist