Electron remote - yaokun123/php-wiki GitHub Wiki

Electron中Remote模块使用

一、Remote

Electron的API方法和模块也是分为可以在主进程和渲染进程中使用。那如果我们想在渲染进程中使用主进程中的模块方法时,可以使用Electron Remote解决在渲染和主进程间的通讯。

这节我们就实现一个通过Web中的按钮打开新窗口。

二、渲染进程中打开新窗口

项目根目录下,新建一个demo2.html文件,然后快速生成html的基本结构,编写一个按钮,引入渲染的js页面。代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <Button id="btn">打开新的窗口</Button><br/>
    <script src="renderer/demo2.js"></script>
</body>
</html>

在render文件夹下,新建一个demo2.js文件,然后编写如下代码。

const btn = this.document.querySelector('#btn')
 const BrowserWindow =require('electron').remote.BrowserWindow

window.onload = function(){
    btn.onclick = ()=>{

         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 name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="background-color: yellow;">
<h1>yellow</h1>
</body>
</html>

修改main.js

var electron = require('electron');     //引入electron模块

var app = electron.app;  // 创建electron引用app

var BrowserWindow = electron.BrowserWindow;  //创建窗口引用

var mainWindow = null ;  //声明要打开的主窗口



app.on('ready',()=>{
    mainWindow = new BrowserWindow({
        width:800,
        height:500,
        webPreferences:{ nodeIntegration:true}
    });  //设置打开的窗口大小

    //mainWindow.loadFile('index.html');  //加载那个页面
    mainWindow.loadFile('demo2.html');  //加载那个页面



    //监听关闭事件,把主窗口设置为null
    mainWindow.on('closed',()=>{
        mainWindow = null
    })

});

然后我们在终端中运行electron .,如果一切正常,就可以顺利打开一个新的窗口,这个窗口可以顺利打开主要的功劳就是electron remote。它让我们有了很多pc端的原生能力

⚠️ **GitHub.com Fallback** ⚠️