在项目中遇到一个需求,需要在electron打开的h5页面中触发事件,返回到electron应用主进程中,进行路由跳转,安装官网中的进程间通信方式实现起来发现监听不到主进程的事件,后来发现是因为事件发送方是子进程,而不是主进程,所以没有监听到,正确示例如下
在vue的electron的预加载文件中代码是这样的
function createWindow() {
require('electron').nativeImage.createFromPath('src/assets/logo.png')
win = new BrowserWindow({
width: 400,
height: 526,
title: "标题",
icon: path.join(__static, 'icon.ico'),
resizable: isDevelopment,
minimizable: false,
skipTaskbar: false,
maximizable: false,
autoHideMenuBar: true,
frame: false,
titleBarStyle: "hidden",
transparent: true,
webPreferences: {
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
enableRemoteModule: true,
webSecurity: false,
contextIsolation: false,
backgroundThrottling:false
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
win.loadURL(mainUrl, { userAgent: "test" }).then()
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL(mainUrl, { userAgent: "test" }).then()
// win.webContents.openDevTools() // todo close
}
// win.openDevTools()
win.on('closed', () => {
win = null
})
}
function webView(args) {
web = new BrowserWindow({
width: args.width ? args.width : 430,
height: args.height ? args.height : 778,
parent: win, // win是主窗口
resizable: isDevelopment,
minimizable: false,
maximizable: false,
darkTheme: false,
titleBarStyle: "hiddenInset",
show: false,
useContentSize: true,
transparent: true,
modal: !!args.modal,
frame: true,
icon: null,
hiddenInMissionControl: false,
webPreferences: {
nodeIntegration: true
}
})
web.loadURL(args.url, { userAgent:args.agent })
//在导航发生改变时主进程发送事件,并且阻止h5的默认行为,禁止前往浏览器打开链接
web.webContents.on('will-navigate', (e, url) => {
//通过h5点击时传递的链接参数,截取需要的参数
const roomId = url.split('/')[url.split('/').length - 1]
room = { ChatroomId: roomId}
win.webContents.send('changerouter',room)
//接收到h5发送的参数,主窗口发送changerouter事件
e.preventDefault()
})
//打开h5触发
web.once('ready-to-show', () => {
if (webUrl != args.url) {
console.log('路径',args.url,'参数',args.agent);
web.show()
webUrl = args.url
}
})
//关闭h5触发
web.on('closed', () => {
if(win){
if(web){
webUrl = ''
web = null
}
}
})
}
vue项目的main.js文件中,添加electron属性
const electron = window.require("electron");
Vue.prototype.$electron = electron;
在底层的vue页面的合适阶段进行监听,如果只需要监听一次可以使用once方法
mounted(){
this.$electron.ipcRenderer.on("changerouter",(e,msg)=>{
函数处理
console.log('msg')
});
},