electron 实现index.html与main.js通讯,获取input输入框数据。

我都知道一个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);执行自己的方法,继续后续逻辑;

畅快使用吧!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值