本文講解如何在渲染進(jìn)程使用主進(jìn)程模塊。
一蛤奢、主/渲染進(jìn)程可使用的模塊
在下面這個(gè)網(wǎng)址可以查到主進(jìn)程和渲染進(jìn)程可使用的模塊忌卤。
https://www.electronjs.org/docs/latest/api/app
在主進(jìn)程矢劲,可以使用app蒲拉、autoUpdater潭苞、BrowerView忽冻、BrowserWindows、clipboard等模塊此疹;在渲染進(jìn)程可以使用clipboard, contextbridge, crashReporter等模塊僧诚。
接下來(lái)我們講如何在渲染進(jìn)程使用主進(jìn)程的模塊。
二蝗碎、渲染進(jìn)程使用主進(jìn)程模塊(未安裝remote模塊)
我們先直接在渲染進(jìn)程使用主進(jìn)程模塊湖笨,看程序會(huì)出什么報(bào)告。
再安裝和調(diào)用remote模塊蹦骑,達(dá)到調(diào)用主進(jìn)程模塊的效果慈省。
BrowserWindow。
1. 修改index.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>
<link rel="stylesheet" href="css/base.css">
<script src="renderer/index.js"></script>
</head>
<body>
<h2>這是渲染進(jìn)程主窗口</h2>
<ul>
<li>主窗口里面的內(nèi)容</li>
<li>主窗口里面的內(nèi)容</li>
<li>主窗口里面的內(nèi)容</li>
<li>主窗口里面的內(nèi)容</li>
<li>主窗口里面的內(nèi)容</li>
</ul>
<button id="btn">打開</button>
</body>
</html>
- 增加index.js文件
index.js實(shí)現(xiàn)的就是點(diǎn)擊按鈕打開一個(gè)窗口的功能眠菇。代碼如下:
/*
嘗試使用主進(jìn)程模塊 - BrowserWindow
*/
const { BrowserWindow } = require("electron");
const path = require("path");
window.onload=()=>{
var btnDom = document.querySelector("#btn");
btnDom.onclick=()=>{
//點(diǎn)周按鈕边败,調(diào)用主進(jìn)程模塊BrowserWindow
const secondWin = new BrowserWindow( {
width: 100,
height: 600,
webPreferences: {
nodeIntegration: true, //允許渲染進(jìn)程使用nodejs
contextIsloation: false //允許渲染進(jìn)程使用nodejs
}
});
secondWin.loadFile(path.join(__dirname,"second.html"));
}
}
運(yùn)行后出現(xiàn)如下報(bào)錯(cuò):
這時(shí),我們來(lái)安裝remote模塊捎废。
三笑窜、渲染進(jìn)程使用主進(jìn)程模塊(正確方法,安裝remote模塊)
在渲染進(jìn)程登疗,通過(guò)remote模塊調(diào)用主進(jìn)程中的怖侦。
1. 安裝remote模塊
npm install --save @electron/remote
2. 在主進(jìn)程加載remote模塊
const { app, BrowserWindow } = require("electron");
const path = require("path");
const remote = require("@electron/remote");
remote.initialize();
const createWindow=()=>{
const mainWindows = new BrowserWindow({
width: 800,
height: 400,
webPreferences: {
nodeIntegration : true, //允許渲染進(jìn)程使用Nodejs
contextIsolation : false //允許渲染進(jìn)程使用Nodejs
}
});
mainWindows.loadFile(path.join(__dirname, "index.html"));
//打開頁(yè)面調(diào)試
mainWindows.webContents.openDevTools();
//打開調(diào)試模式
remote.enable(mainWindows.webContents);
}
//監(jiān)聽(tīng)?wèi)?yīng)用的啟動(dòng)事件
app.on("ready", createWindow);
主要是下面三條代碼:
const remote = require("@electron/remote");
remote.initialize();
remote.enable(mainWindows.webContents);
3. 在渲染進(jìn)程修改BrowswerWindow引入方式
在index.js文件,將
const { BrowserWindow } = require("electron");
改為
const { BrowserWindow } = require("@electron/remote");
運(yùn)行谜叹,點(diǎn)擊打開按鈕匾寝,即成功新建了一個(gè)窗口。
最后更新時(shí)間:2022年2月15日