Learn how to check with JavaScript if your code is being executed inside Electron or the browser.

With all the available frameworks of today like ReactJS, AngularJS etc. the development process speeds up and optimizes as never before the performance of web applications. Thanks to Electron you are able to package such web applications inside a desktop application. Pityfully, features like hot reload aren't available in Electron aren't available so you will want sometimes to work directly in the browser as you do always with your web app. This leads to a basic necessity, know when you are inside electron or the browser with JavaScript to execute some code on every platform, as you wouldn't want to maintain 2 code bases.

Fortunately, to know when you're inside Electron or the Browser is pretty easy and we'll show you how to achieve it in this article.

A. Install isElectron module

The isElectron module is a tiny utility that allows you to know when you are inside the Electron platform or a common browser. Install this module by switching to the directory of your project with the terminal and executing the following command:

npm install --save is-electron

After the installation you will be able to require the is-electron module anywhere and verify which platform you are using:

let isElectron = require("is-electron");

if(isElectron()){
    console.log("Electron aww yeahhh !");
}else{
    console.log("Running in other platform as a normal browser");
}

For more information about this module, please visit the official repository at Github here.

B. Use isElectron function

If you are not willing to install a module for the function that offers the isElectron module, you can simply use it and include it within your own code:

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

And use it in the same way that the module does:

if(isElectron()){
    console.log("Electron aww yeahhh !");
}else{
    console.log("Running in other platform as a normal browser");
}

Both ways work in the Renderer process and the Main process. The function and the module were written by @cheton.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors