通过 JavaScript 检测 Electron 实例

Gia*_*ini 7 javascript electron

我有一个 web 应用程序,它将在网站上运行并作为独立的 Electron 实例(对于 Windows 为 .exe)。

我想通过 JavaScript 判断 web 应用程序是否在 ElectronJS 中运行,以便显示在线版本的一些额外功能。有没有办法检测Electron框架实例?我想避免编写两个略有不同的网络应用程序版本。

Ale*_*lex 11

只需使用此代码(从 is-electron“库”获取)

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;
}
Run Code Online (Sandbox Code Playgroud)


Jus*_*nas 5

基于电子问题

  • 对于主脚本,它们作为 Node 进程运行,因此使用process.versions.hasOwnProperty('electron')或等效的

  • 对于渲染器脚本,它们在浏览器中运行,因此使用/electron/i.test(navigator.userAgent)或等效的