我都知道一个electron程序 需要 index.html,main.js,package.json;
这一点其他文章都有讲述 我就不再赘述了;
可以参考:
Electron桌面应用打包流程
本文着重讲述,如何实现将index.html中的输入数据,转给主进程做其他操作。
可想一个场景:我们实现了一个爬虫程序,但是id需要由electron的index.html来获取,输入后,交由主程序main.js继续其他爬虫操作;
想到的方式就是主进程跟渲染进程的通讯实现;
首先创建一个主进程通讯模块
// ipcMain.js 模块
const { ipcMain } = require('electron');//引入主进程模块
const { poerFun } = require('./poer.js'); // 自己需要执行的方法js文件
ipcMain.on('AsynMsg',async (event, data) => {
// data就是输入框的信息
await poerFun(data);
event.sender.send('ReturnAsynMsg', '异步通信返回')
})
其次创建一个渲染进程模块
// ipcRenderer.js 模块
const { ipcRenderer } = require('electron')//引入渲染进程模块
ipcRenderer.on('ReturnAsynMsg', (event, data) => {
alert('完成');
})
分别引入到main.js
const { app, BrowserWindow } = require('electron');
const { poerFun } = require('./poer.js');
let win;
let windowConfig = {
width:800,
height: 600,
webPreferences: {
contextIsolation: false,
nodeIntegration: true, // 设置开启nodejs环境
enableRemoteModule: true // enableRemoteModule保证renderer.js可以可以正常require('electron').remote,此选项默认关闭且网上很多资料没有提到
}
};
function createWindow(){
win = new BrowserWindow(windowConfig);
win.loadURL(`file://${__dirname}/index.html`);
// poerFun();
//开启调试工具
win.webContents.openDevTools();
win.on('close',() => {
//回收BrowserWindow对象
win = null;
});
require('./ipcMain.js');//引入主进程模块
win.on('resize',() => {
win.reload();
})
}
app.on('ready',createWindow);
app.on('window-all-closed',() => {
app.quit();
});
app.on('activate',() => {
if(win == null){
createWindow();
}
})
渲染进程模块 引入index.html中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>hello electron</h1>
<form>
<input style="width:60%;" id="input" type="text" placeholder="请输入id" />
</form>
<button onclick="btn()">确认id</button>
<!-- <button id="sendAsny">异步通讯</button>
<button id="sendSync">同步通讯</button> -->
<script src="./ipcRenderer.js"></script>
<script>
function btn() {
var x = document.getElementById("input")//获取输入框元素
ipcRenderer.send('AsynMsg', x.value);
}
</script>
</body>
</html>
至此,main.js中的ipcMain,可以获取data数据,即为input的数据,await poerFun(data);执行自己的方法,继续后续逻辑;
畅快使用吧!