【问题标题】:How to properly use preloads and window.api calls in electron?如何在电子中正确使用预加载和 window.api 调用?
【发布时间】:2021-03-28 21:21:02
【问题描述】:

我在使用 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

【问题讨论】:

    标签: javascript node.js electron ipc preloadjs


    【解决方案1】:

    根据docs

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      相关资源
      最近更新 更多