通过JavaScript检测电子实例

我有一个webapp,它将作为独立的Electron实例(适用于Windows的.exe)在网站上运行。

我想通过JavaScript告诉webapp是否在ElectronJS内运行,以便显示在线版本的一些其他功能。有什么方法可以检测电子框架实例吗?我想避免编写两个稍微不同的webapp版本。

评论
  • Oo晓oO
    Oo晓oO 回复

    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

  • lipsum
    lipsum 回复

    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;
    }
  • qq网名
    qq网名 回复

    you can use for simplicity a library named is-electron

    或者您可以尝试使用类似的东西

    if (typeof electron !== 'object') return false;