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;
}
通过preload在window预注入一个检测变量
const { contextBridge: bridge } = require('electron');
bridge.exposeInMainWorld('checkElectron', {
isInElectron: () => {
if (isElectron()) {
return true;
}
return false;
}
});
渲染进程直接可通过判断 window.checkElectron.isInElectron()
来确定当前执行环境是否是electron,如果没有checkElectron
那说明当前环境就是浏览器环境,变量没有被注入