首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ContextBridge在preload.js中仍未定义,给出了错误:无法读取封装的电子应用程序中未定义的属性“exposeInMainWorld”?

ContextBridge在preload.js中仍未定义,给出了错误:无法读取封装的电子应用程序中未定义的属性“exposeInMainWorld”?
EN

Stack Overflow用户
提问于 2020-07-21 21:50:28
回答 2查看 3.2K关注 0票数 2

我有一个用电子包裹的角度应用程序。我使用电子构建器生成了安装程序。根据与呈现程序进程通信的建议,我使用了preload.js作为preload脚本。

该脚本在开发环境中运行良好。但是,一旦我打包并安装了该应用程序,它就会显示错误无法读取未定义的属性'exposeInMainWorld‘。

这是我的preload.js

代码语言:javascript
复制
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));
            }
        }
    }
    );
};

My Main.js

代码语言:javascript
复制
        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.jspreload.js保存在根级的文件夹电子中,其中package.json是可用的。如果您需要检查我的builder-config.yaml,它就在此链接上。

请建议一下该怎么做。

P.S.:在开发模式下工作非常好。这个问题只是在用电子构建器打包应用程序之后才出现的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-01 17:07:28

我让这个开始工作了。实际上,在我的builder-config.yaml中提到的电子版本是5.0.13。那时还没有引入contextbridge api。当我将电子的版本改为9或更高时,它工作得很好。谢谢

票数 0
EN

Stack Overflow用户

发布于 2020-07-28 14:53:20

当我写到:

代码语言:javascript
复制
getPlatform: () => window.remote.getPlatform(),

然后我得到了Uncaught Error: Uncaught TypeError: Cannot read property 'getPlatform' of undefined

在……里面

代码语言:javascript
复制
console.log('window.remote.getPlatform()', window.remote.getPlatform && window.remote?.getPlatform())

当我把它改成

代码语言:javascript
复制
getPlatform: () => process.platform,

一切都很好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63023636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档