从渲染器进程未接收到主进程发起的电子通道消息

时间:2016-11-11 14:04:20

标签: javascript node.js electron

我正在构建一个带有操作系统托盘菜单的电子应用程序。

tray menu

在主要过程中,我想听取“关于”菜单项的点击,然后通知渲染器进程,以便它可以相应地更新窗口的视图。

这是我渲染窗口和托盘菜单时主要过程的部分:

const {app, BrowserWindow, Menu, Tray} = require('electron')
const appConfig = require('./appConfig')
const ipc = require('electron').ipcMain
const path = require('path')
const config = require('../config')

let win, tray

function createWindow(){
    win = new BrowserWindow({
        height: appConfig.window.height,
        width: appConfig.window.width
    })

    win.loadURL(`file://${__dirname}/client/index.html`)

    if(appConfig.debugMode){
        win.webContents.openDevTools()
    }

    win.on('closed', () => {
        win = null
    })
}

function setTrayIcon(){
    tray = new Tray(path.resolve(__dirname, './assets/rocketTemplate.png'))
    tray.setToolTip('Launch applications by group')

    let menuitems = config.groups.map(group => {
        return {label: `Launch group: ${group.name}`}
    })
    win.webContents.send('ShowAboutPage' , {msg:'hello from main process'});
    win.webContents.send('ShowAboutPage')

    menuitems.unshift({type: 'separator'})

    // Here where I add the "About" menu item that has the click event listener
    menuitems.unshift({
        label: 'About AppLauncher',
        click(menuitem, browserWin, event){
            // sending a log to the console to confirm that the click listener did indeed hear the click
            console.log('about menu clicked')
            win.webContents.send('ShowAboutPage')
        }
    })
    menuitems.push({type: 'separator'})
    menuitems.push({label: 'Quit AppLauncher'})

    const contextMenu = Menu.buildFromTemplate(menuitems)
    tray.setContextMenu(contextMenu)
}

app.on('ready', () => {
    createWindow()
    setTrayIcon()
})

这是应该监听频道消息的渲染器脚本:

const Vue = require('vue')
const App = require('./App.vue')
const ipc = require('electron').ipcRenderer

ipc.on('ShowAboutPage', () => {
    console.log('show about fired in store')
    alert('show about fired in store')
    this.notificationMessage = 'Show about page'
})


require('./style/base.sass')

new Vue({
    el: '#app',
    render: h => h(App)
})

当我单击托盘中的“关于”菜单时,我从主进程获得console.log输出,但我从未在渲染器进程中收到console.log或alert。

我的应用程序只有一个窗口(由窗口关闭时win变量的无效证明)所以它似乎不是我将消息发送到错误的渲染器进程的问题。

我浏览了electron documentation on using webContents to send messages to renderer instances,看起来我的代码结构正确,但显然我遗漏了一些东西。

有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

尝试将您的渲染器脚本重写为

const { ipcRenderer } = require("electron");
ipcRenderer.on("ShowAboutPage", () => {
    //etc
});