Detect Electron or Web page running?


#1

Sorry this seams like a very basic question - but I just cannot find an answer!

In the script code in the render window is there an easy way to determine if the app in running in a web page or in Electron?


#2

Pretty much just check whether require exists and a window variable exists. To be extra safe, you could also try...catch requiring 'electron':

function isElectron() {
  if (typeof require !== 'function') return false;
  if (typeof window !== 'object') return false;
  try {
    const electron = require('electron');
    if (typeof electron !== 'object') return false;
  } catch(e) {
    return false;
  }
  return true;
}

#3

Here’s another alternative:

function isElectron() {
  return process && process.versions && (process.versions.electron !== undefined);
}

#4

@facekapow
Thanks function returned correct answer both in Electron and web page.

@enlight
Thanks function returned correct answer in electron but returned error (process is not defined) in web page - but easy to correct with a try catch.


#5

Which browser are you using?

Seems like something that should work fine, so it’d be good to know where it’s going wrong.


#6

@caffiend

The have only checked it using Chrome but the two solutions provided answered the question!


#7

You’re not wrong! That’s good to know, anyway.


#8

This should make enlight’s answer work in any browser

function isElectron() { return (typeof process !== "undefined") && process.versions && (process.versions.electron !== undefined); }

Sorry about formatting but the key is that if an identifiers is undefined you need to use “typeof” to safely check it’s existence.


#9

Thanks @etraub I am using that checking system now.

I an trying to maintain one code base which will work for both systems - webpages and Electron - but it is hard not to resist branching off in Electron to take advantage of other features!


#10

The way I check for Electron (my app is a Cordova/Electron app, rather than a Web/Electron app), is that I set a global variable from the main.js file, and then I can just check for it in the app: mainWindow.webContents.executeJavaScript("window.electronFlag=true;")


#11

@caffiend

My next step is to take my Electron app and use Cordova so that it will run on Android - I have been told take this is very easy but I have not found any examples - could you possibly detail your experience of using Electron with Cordova.


#12

It’s easy.

The major difference is using Cordova plugins rather than Node modules to achieve non-web functionality. So I have a JS file that gives me some helper methods for writing files, etc, that behave the same but use the relevant plugin/module for the right platform.