gpt4 book ai didi

javascript - 如何在 Electron 中正确使用preloads和window.api调用?

转载 作者:行者123 更新时间:2023-12-03 12:38:12 24 4
gpt4 key购买 nike

我在使用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.html中链接的passwordPage.js:
document.getElementById("login").addEventListener('click', function() {
window.api.send("login", "test");
})
passwordPage控制台中的错误:
Uncaught TypeError: Cannot read property 'send' of undefined

最佳答案

根据docs:

The value should be the absolute file path to the script.


尝试使用 `${__dirname}/preload.js`或相等的名称。

关于javascript - 如何在 Electron 中正确使用preloads和window.api调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65353344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com