electron 窗口直接交互
使用ipc 协议,进程之间的通讯
ipcMain 用于主进程
ipcRenderer 用于子进程
下面例子是主进程和子进程通讯
说明里面是,点击创建一个新窗口,带参数,然后新窗口接受到,并展示,然后点击新窗口按钮,向主窗口发送数据,主窗口,收到展示,并给子窗口返回信息,的过程
下面是主窗口代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h2></h2>
<button onclick="chuan()">发送数据</button>
</body>
<script>
const remote = require('electron').remote;
const {
BrowserWindow,
ipcMain
} = remote
ipcMain.on('hui', (e, data) => {
console.log(data.wo);
document.getElementsByTagName('h2')[0].innerText = data.wo
e.reply('reply', 'pong')
});
function chuan() {
let zi = new BrowserWindow({
width: 600,
height: 600,
show: false,
webPreferences: {
nodeIntegration: true, //开启node功能
}
})
zi.webContents.openDevTools()
zi.on('closed', () => {
zi = null
})
zi.loadFile('zi.html')
zi.on('ready-to-show', () => {
zi.show()
zi.webContents.send('data', {
xing: '男',
age: 25
})
})
}
</script>
</html>
下面是子窗口代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body onload="onload()">
我是子窗口
<h1></h1>
<h1></h1>
<h1></h1>
<button onclick="chuan()">发送数据</button>
</body>
<script>
const remote = require('electron').remote;
let ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('reply', (e, arg) => {
console.log(arg)
document.getElementsByTagName('h1')[2].innerText = arg
})
function onload() {
let ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('data', (e, data) => {
console.log(data);
document.getElementsByTagName('h1')[0].innerText = data.xing
document.getElementsByTagName('h1')[1].innerText = data.age
})
}
function chuan() {
console.log(4141111);
ipcRenderer.send('hui', {
wo: 46512131
})
}
</script>
</html>