Error: contextBridge API can only be used when contextIsolation is enabled

3 篇文章 0 订阅
3 篇文章 0 订阅

electron项目中preload.js文件使用下面的方法时报错

const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronApi', {
    
});

在这里插入图片描述

node:electron/js2c/renderer_init:2 Unable to load preload script: D:\Vue\wnpm\electron\preload.js
(匿名) @ node:electron/js2c/renderer_init:2
node:electron/js2c/renderer_init:2 Error: contextBridge API can only be used when contextIsolation is enabled
    at checkContextIsolationEnabled (node:electron/js2c/renderer_init:2:5071)
    at Object.exposeInMainWorld (node:electron/js2c/renderer_init:2:5182)
    at Object.<anonymous> (D:\Vue\wnpm\electron\preload.js:3:15)
    at Object.<anonymous> (D:\Vue\wnpm\electron\preload.js:35:3)
    at Module._compile (node:internal/modules/cjs/loader:1391:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1451:10)
    at Module.load (node:internal/modules/cjs/loader:1214:32)
    at Module._load (node:internal/modules/cjs/loader:1030:12)
    at c._load (node:electron/js2c/node_init:2:13672)
    at s._load (node:electron/js2c/renderer_init:2:31018)

这个错误提示表明,在启用了上下文隔离(contextIsolation)的情况下,才能使用 contextBridge API。上下文隔离是 Electron 中一种安全机制,用于保护渲染进程免受主进程的恶意代码的影响。

通过 contextBridge.exposeInMainWorld 方法,你可以在渲染进程中暴露指定的 Electron API,以便在渲染进程中安全地访问。然而,如果未启用上下文隔离,或者启用了上下文隔离但未正确配置,就会出现报错。

要解决这个问题,你需要确保在创建 BrowserWindow 实例时启用了上下文隔离,并且正确配置了 preload 脚本。在创建 BrowserWindow 实例时,需要将 contextIsolation 设置为 true,并将 preload 脚本指定为要注入到渲染进程中的预加载脚本。

示例代码如下:

const { BrowserWindow } = require('electron');

// 创建 BrowserWindow 实例时,启用上下文隔离,并指定 preload 脚本
const mainWindow = new BrowserWindow({
  webPreferences: {
    contextIsolation: true,//注意这个关键配置
    preload: path.join(__dirname, 'preload.js')
  }
});

确保按照以上步骤正确配置了 BrowserWindow 实例后,再次尝试使用 contextBridge.exposeInMainWorld 方法来暴露 Electron API,应该就不会再出现报错了。

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值