背景:
最近在搞electron+vue项目,有几个业务需要用到vue和Electron通信,于是打开了electron官网,跟着敲代码,但是用到contextBridge去暴露electron的时候,在控制台调用window.electron一直为undefined。
找问题找了一天,几近崩溃,最后发现是因为一个属性的设置。简单记录一下。
解决:
win = new BrowserWindow({
width: 800,
height: 600,
webSecurity: true, // 允许加载本地文件
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: false,
contextIsolation: false, //问题所在!!!!!
},
})
把contextIsolation设置为true,问题就解决了。
当contextIsolation 属性是false的时候一直会报错这个。需要改为true。
下面是我的所有配置:
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
lintOnSave: false,
transpileDependencies: true,
//添加electron集成,开启node功能
pluginOptions: {
electronBuilder: {
preload: "src/preload.js",
},
}
})
preload.js
import { contextBridge, ipcRenderer } from "electron";
contextBridge.exposeInMainWorld("electron", {
ipcRenderer,
});
具体原因可查看electron官网。。(个人感觉electron官网写的很垃圾,很不友好)
还是自己百度搜吧。