1、首先要下载remote模块
yarn add @electron/remote
2、在主进程初始化@electron/remote模块,然后在渲染中使用
require('@electron/remote/main').initialize()
require('@electron/remote/main').enable(mainWindow.webContents)
主进程
var electron = require("electron");
var app = electron.app; //引用app
var BrowserWindow = electron.BrowserWindow; //窗口引用
var mainWindow = null; //声明要打开的主窗口
app.on("ready", () => {
mainWindow = new BrowserWindow({
width: 800,
height: 800,
webPreferences: { nodeIntegration: true,contextIsolation:false,enableRemoteModule: true, },
});
require('@electron/remote/main').initialize()
require('@electron/remote/main').enable(mainWindow.webContents)
mainWindow.loadFile("demo.html"); //加载html页面
mainWindow.on("closed", () => {
mainWindow = null;
});
});
demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">打开新窗口</button>
<script src="./render/demo.js"></script>
</body>
</html>
demo.js
const btn = document.querySelector("#btn")
const BrowserWindow = require('@electron/remote').BrowserWindow
window.onload = function() {
btn.onclick = function() {
newWin = new BrowserWindow({width:500,height:500})
newWin.loadFile('yellow.html')
newWin.on('close', () => {
newWin = null
})
}
}
yellow.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
111asdasdasdasd
</body>
</html>