electron新版本中使用remote

electron remote的问题

electron有主进程和渲染进程之分,主进程可以简单理解为mian.js也就是主程序运行后的窗体,而渲染进程则是mian.js中所创建的窗体通过loadFile()加载的HTML页面的进程,在渲染进程中可以通过按钮单击创建新的窗体,但是无法直接使用BrowserWindow,而是需要使用remote。
remote本来是用于在渲染进程中打开新窗体的。但是新版本的electron和旧版本的electron用法存在差异。
以下是新版本的使用方式

1.安装

npm install --save @electron/remote

2.在主程序中引入和初始化

安装好remote之后,我们需要在主进程和渲染进程中进行相应的设置才能使用。
首先是在主程序中引入和初始化remote。

const remote = require("@electron/remote/main")
remote.initialize()
//...
remote.enable(mainWindow.webContents)

具体引入的时机和位置可以参考后文中的实例的main.js代码。

3.在渲染进程中require

//以前的写法
const {BrowserWindow} = require("electron").remote
//现在的写法
const {BrowserWindow} = require("@electron/remote")

实例

本例实现在窗口加载的页面中单击按钮打开新窗体
注意:webPreferences的两个属性必须写上,否则渲染进程将无法使用NodeJS

main.js

const { app,BrowserWindow,ipcMain,shell} = require("electron")
const remote = require("@electron/remote/main") //1 
remote.initialize()//2

let mainWindow = null

// require("./menu.js")

app.on("ready",()=>{
    mainWindow = new BrowserWindow({
        width:300,
        height:300,
        webPreferences:{
            nodeIntegration:true,//允许渲染进程使用nodejs
            contextIsolation:false//允许渲染进程使用nodejs
        }
    })
    mainWindow.loadFile("index.html")
    mainWindow.on("closed",()=>{
        mainWindow = null
    })
    remote.enable(mainWindow.webContents)//3
})

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>点击页面按钮打开新窗口title>
head>
<body>

<input type="button" value="打开新窗口" id = "btn1">
<script src="remote.js">script>
body>
html>

remote.js

const {BrowserWindow} = require("@electron/remote")

const btn1 = document.querySelector("#btn1")

const baidu_site = "https://www.baidu.com"

window.onload = ()=>{
    btn1.onclick = ()=>{
        win = new BrowserWindow({
            width:500,
            height:500,
        })
        win.loadFile("page2.html")
    }
}

运行效果

点击主窗体加载页面index.html中的“打开新窗口”按钮,就会打开“窗口2”
electron新版本中使用remote_第1张图片

你可能感兴趣的:(Electron,electron,javascript,前端)