如何正确使用电子中的预加载和window.api调用



我在使用render.js文件编写"api";从渲染的html页面的javascript调用。

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");
})

密码控制台错误页码:

Uncaught TypeError: Cannot read property 'send' of undefined

根据文档:

该值应该是脚本的绝对文件路径

尝试使用`${__dirname}/preload.js`或类似的值。

最新更新