我在使用 render.js 文件从呈现的 html 页面的 javascript 编写“api”调用时遇到问题。
main.js 新增 BrowserWindow 功能包括:
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: "preload.js" // use a preload script
},
preload.js:
const { ipcRenderer, contextBridge } = require('electron')
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
let validChannels = ["login"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
passwordPage.js 链接在 passwordPage.html 中:
document.getElementById("login").addEventListener('click', function() {
window.api.send("login", "test");
})
passwordPage 控制台中的错误:
Uncaught TypeError: Cannot read property 'send' of undefined