There are several ways to solve this problem. The first is to request the platform about its capabilities. For example, Electron sets a variable:
process.versions.electron
This will not be installed if you work in a browser, so you can check its existence (and you will find out that you work in Electron). Here's the documentation: Electron: Process .
Testing for an attached property can be a little rude, so a slightly simpler way is to wrap an attempt to access the value in try / catch:
try { process.versions.electron; } catch (err) { console.log('Not electron', err); }
You can even wrap it in a nice function:
function isPlatformElectron() { 'use strict'; try { process.versions.electron; return true; } catch (err) { return false; } } if (isPlatformElectron()) {
Alternatively, you can do something similar with the source code (slightly modified):
let app, BrowserWindow; try { ({app, BrowserWindow} = require('electron')); } catch (err) { console.log('Not electron'); } if (app && BrowserWindow) { console.log('is electron'); }
I find this version more difficult to read and prefer the approach to functions suggested above, but I thought it would be useful to set an example using destructuring like your original (although in this case you cannot use const).
source share