模拟主进程与渲染进程的通讯过程
渲染进程
根目录下添加renderer.js,既支持node js也支持dom js,示例代码如下:
点击查看代码
//这是渲染进程
const {ipcRenderer}=require("electron")
//下面是从渲染进程向主进程发送消息
window.addEventListener('DOMContentLoaded',()=>{
ipcRenderer.send("message","I am from the rendering process!")
ipcRenderer.on("reply",(event, args)=>{
document.getElementById('message').innerHTML=args
})
})
点击查看代码
const {app,BrowserWindow,ipcMain}=require("electron")
//ready:当electron完全加载,准备好创建BrowserWindow的时候
app.on('ready',()=>{
const win=new BrowserWindow({
width:800,
height:600,
webPreferences:{
//意思是在man.js中可以使用nodejs的api
nodeIntegration:true,
//加上这段代码后支持node Api
contextIsolation: false
}
})
win.loadFile("index.html");
ipcMain.on("message",(event, args)=>{
console.log(args)
// event.sender.send("reply","I am the main process,Over!")
// event.sender和win是一样的
win.send("reply","I am the main process,Over!")
})
})
点击查看代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<link href="./styles.css" rel="stylesheet">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<p id="message"></p>
<!--渲染进程添加-->
<script src="./renderer.js"></script>
</body>
</html>