让HTML页与主进程通信
index.js的关键代码:
new BrowserWindow({
width: 1300,
height: 768,
webPreferences: {
nodeIntegration: true,
preload: __dirname+ '/preload.js', // 预加载js文件 使web页面可以使用electron的api
}
});
测试接受消息:
ipcMain.on('message-to-index', (event, message) => {
console.log('来自web端的消息:',message);
});
preload.js代码:
// preload.js
const { contextBridge, ipcRenderer } = require('electron');
// 将ipcRenderer封装到一个全局变量中
contextBridge.exposeInMainWorld('eleMsg', {
send: (channel, data) => {
ipcRenderer.send(channel, data);
},
receive: (channel, func) => {
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
});
HTML页:
window.eleMsg.send('message-to-index', 'Hello from the HTML page!');
隐入托盘等其它代码在此下载:
https://gitee.com/flashme/myjs/tree/master/node/electron
(示例index.js还包括启动koa2服务、新增静态资源路径、端口自适应)
Comments | NOTHING