Detect an Electron instance via JavaScript

Viewed 4473

I have a webapp which will run on a website and as a standalone Electron instance (.exe for Windows).

I'd like to tell via JavaScript if the webapp is running inside ElectronJS or not, in order to display some extra features for the online version. Is there any way to detect the Electron framework instance? I'd like to avoid writing two slightly different versions of the webapp.

4 Answers

Just use this code (got it from is-electron "library")

function isElectron() {
    // Renderer process
    if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
        return true;
    }

    // Main process
    if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {
        return true;
    }

    // Detect the user agent when the `nodeIntegration` option is set to true
    if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {
        return true;
    }

    return false;
}

Based on electron issue:

  • For main scripts, they're running as a Node process, so use process.versions.hasOwnProperty('electron') or equivalent

  • For renderer scripts, they're running in the browser, so use /electron/i.test(navigator.userAgent) or equivalent

Electron exposes full access to Node.js both in the main and the renderer process.

Source: Electron Application Architecture

This means that in your renderer thread (i.e. the user-facing part of your application) you can access NodeJS native modules such as fs.

I would recommend adopting a similar approach to browsers: avoid user-agent-based conditionals and prefer a is-this-feature-available? model if you can:

// renderer.js
try {
  const fs = require('fs');
  // test something (quick) that only the `fs` module can do
} catch (e) {
  // probably not an electron app
}

However please do read https://www.electronjs.org/docs/tutorial/security first!


Further thoughts

Presumably you must somehow derive two artefacts from one single codebase: a web app and a desktop app.

You could perhaps consider injecting/exposing an environment variable during the build process assuming you can run two different build configurations.

you can use for simplicity a library named is-electron

Related