我有一个包裹在Electron中的角度应用程序。我已经使用 Electron 生成器生成了安装程序。根据与渲染器进程通信的建议,我已将preload.js
用作preload
脚本。
该脚本在开发环境中可以正常工作。但是,一旦打包并安装了应用程序,它将显示错误无法读取未定义的属性'exposeInMainWorld'
这是我的preload.js
window.onload = () => {
const {
contextBridge,
ipcRenderer
} = require("electron");
const validChannels = ['event-1', 'event-2', 'event-3'];
// Expose protected methods that allow the renderer process to use the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels To Main Process
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
// From Main Process
if (validChannels.includes(channel)) {
console.log('receive: ' + channel);
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
};
我的Main.js this._win = new BrowserWindow({
width: 1024,
height: 768,
webPreferences: {
nodeIntegration: false,
webSecurity: true,
allowEval: false,
allowRunningInsecureContent: false,
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "./preload.js") // use a preload script
},
title: this._appTitle,
autoHideMenuBar: true,
icon: path.join(__dirname, '/../dist/some-path/favicon.ico')
});
我将main.js
和preload.js
都保留在根目录中的文件夹 Electron 文件中,该文件夹可以使用package.json
。如果您需要检查我的builder-config.yaml
,它位于this link。请提出建议。
P.S. :在开发人员模式下,
preload.js
绝对可以正常工作。问题仅在将应用程序与 Electron 生成器打包在一起之后
最佳答案
我写的时候遇到了这样的错误:
getPlatform: () => window.remote.getPlatform(),
然后我得到Uncaught Error: Uncaught TypeError: Cannot read property 'getPlatform' of undefined
在console.log('window.remote.getPlatform()', window.remote.getPlatform && window.remote?.getPlatform())
当我将其更改为getPlatform: () => process.platform,
一切正常。
关于javascript - ContextBridge在preload.js中仍然未定义,给出错误: Cannot read property 'exposeInMainWorld' of undefined in packaged Electron app?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63023636/