【问题标题】:Electron channel messages initiated from the main process not received by the renderer process渲染器进程未收到从主进程发起的电子通道消息
【发布时间】:2017-03-25 18:46:53
【问题描述】:

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

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

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

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 或警报。

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

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

有什么想法吗?

【问题讨论】:

    标签: javascript node.js electron


    【解决方案1】:

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

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

    【讨论】:

    • 您好,谢谢您的回复。从功能上讲,我的代码和您提出的代码更改没有区别。它只是重命名变量。
    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2022-01-15
    • 2022-01-27
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2016-07-05
    • 2021-11-11
    相关资源
    最近更新 更多