使用版本
父窗口打开子窗口,使用remote模块的时候,出现了以下的问题:
const BrowserWindow = require('electron').remote.BrowserWindow
解决方案:
1、首先在自己项目中npm安装 @electron/remote模块
yarn add @electron/remote
2、在主进程初始化@electron/remote模块,然后在渲染中使用
require('@electron/remote/main').initialize()
require('@electron/remote/main').enable(mainWindow.webContents)
3、在主进程main.js中,设置remote模块,在webPreferences中添加enableRemoteModule:true 和 contextIsolation为false。
webPreferences:{
nodeIntegration:true,
enableRemoteModule: true,
contextIsolation: false
}
4、渲染进程中,require('electron').remote替换为require('@electron/remote')
const BrowserWindow = require('@electron/remote').BrowserWindow
代码:
主进程main.js:
// 主进程main.js
var electron = require("electron") ;
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
let mainWindow = null;
app.on("ready", () => {
mainWindow = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false
}
});
require('@electron/remote/main').initialize();
require('@electron/remote/main').enable(mainWindow.webContents);
mainWindow.loadFile("./demo2.html");
mainWindow.on("closed", () => {
mainWindow = null;
})
})
渲染进程demo2.js:
//demo.js
var btn = this.document.querySelector("#btn");
const BrowserWindow = require('@electron/remote').BrowserWindow
let newWin;
window.onload = function(){
btn.onclick = () => {
newWin = new BrowserWindow({
width: 500,
height: 500,
})
newWin.loadFile("yellow.html");
newWin.on("close", () => {
newWin = null;
})
}
};