学习Electron时,在渲染进程中通过remote打开开发这工具,发现点击按钮没有反应。
const remote = require('electron').remote;
let openDevToolsBtn = document.querySelector("#openDevToolsBtn");
openDevToolsBtn.addEventListener('click', function() {
alert(remote);
remote.getCurrentWindow().webContents.openDevTools();
});
打印remote对象时,发现是 undefined
。
- 问题原因
在网上搜了一下,发现是electron 10下,remote默认关闭,需要手动开启。
- 解决方案
找到项目中的BrowserWindow
定义部分,手动设置webPreferences
中的enableRemoteModule
为true
即可,添加部分如下:
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true, // 赋予此窗口页面中的JavaScript访问Node.js环境的能力
// 在electron 10.0.0之后,remote模块默认关闭
// 必须手动设置webPreferences中的enableRemoteModule为true之后才能使用
enableRemoteModule: true, // 打开remote模块
}
});
- 参考资料