Electron与前端通信ipc
const electron = require('electron')
const { app } = electron
const ipc = require('electron').ipcMain
const { BrowserWindow } = electron
let win
ipc.on('getMsg', (sys, msg) => {
console.log(msg) //接收窗口传来的消息
})
app.on('ready', createWindow)
app.on('window-all-cloased', () => {
if (process.platform !== 'drawin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
function createWindow() {
win = new BrowserWindow({
width: 600,
height: 400
})
win.loadURL(`file://${__dirname}/app/index.html`)
// win.webContents.openDevTools() //开启调试工具
win.on('close', () => {
win = null
})
win.on('resize', () => {
win.reload()
})
win.on('closed', () => {
win = null
})
}
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>myapp</title>
</head>
<body>
<h1>electron-app-3</h1>
<input type="" name="" id="ipt" value="">
<button type="button" onclick="connectMain()">和主进程通信</button>
<script>
const ipc = require('electron').ipcRenderer;
var ipt = document.getElementById('ipt')
function connectMain() {
console.log('index.html', ipt.value);
ipc.send('getMsg', ipt.value)
}
</script>
</body>
</html>

本文介绍了一个使用Electron框架实现的简单应用程序,展示了如何通过IPC (Inter-Process Communication) 实现前端页面与主进程之间的消息传递。具体包括:主进程监听前端发送的消息并打印,前端页面通过按钮触发消息发送到主进程。
215

被折叠的 条评论
为什么被折叠?



