通过JavaScript检测Electron实例

7

我有一个网络应用程序将在网站和独立的Electron实例(Windows中的.exe文件)上运行。

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


2
这可能会有所帮助:https://github.com/electron/electron/issues/2288 - Felix Kling
4个回答

11

只需使用这段代码(从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;
}


该源代码还包含一个非常有用的链接,指向@Justinas的答案中提到的相同的electron问题#2288 - icc97

5

根据Electron问题

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

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


userAgent 代码是该问题中 早期评论 的一个版本:const userAgent = navigator.userAgent.toLowerCase(); const isElectron = userAgent.indexOf(' electron/') > -1; 我发现这种写法更冗长但更易读。同时,我也在想 ' electron/' 相对于 /electron/i 会捕获哪些边缘情况。 - icc97
1
@icc97 /electron/i 匹配包含 anotherElecronification 的用户代理,并且 electron/ 匹配不以 electron/ 开头但包含完全相同短语的用户代理。 - Justinas

0
Electron在主进程和渲染进程中均提供对Node.js的完全访问权限。这意味着在您的渲染线程(即应用程序的用户界面部分),您可以访问Node.js的本地模块,比如fs
我建议采用类似于浏览器的方法:避免基于用户代理的条件,如果可以的话,更倾向于使用“这个特性是否可用?”的模式。
来源:Electron应用程序架构
// renderer.js
try {
  const fs = require('fs');
  // test something (quick) that only the `fs` module can do
} catch (e) {
  // probably not an electron app
}

然而请先阅读https://www.electronjs.org/docs/tutorial/security


进一步思考

假设你必须从一个单一的代码库中派生出两个工件:一个 Web 应用程序和一个桌面应用程序。

在构建过程中,你可以考虑注入/暴露环境变量,假设你可以运行两个不同的构建配置。


-2

为了简单起见,您可以使用一个名为is-electron的库。


1
如果我声明 window.electron = {} 会怎样? - Justinas
从 is_electron 代码中翻译:`function isElectron() { // 渲染进程 if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') { return true; }// 主进程 if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) { return true; } ... return false;}` - alessandro boschini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接