从 Main 向 Renderer 发送消息

Jok*_*ini 5 javascript node.js electron

有人可以帮我吗?我完全不知道如何解决这个问题。我现在花了大约一周的时间试图找到解决方案,但效果不佳,而且网上似乎缺乏可靠的解决方案。我已经创建了一个 github 存储库来尝试演示这个问题。

简而言之,我在我的应用程序中实现了一个状态栏,我想用各种字符串消息填充它。这些消息将从导入 Electron 的 js 文件中包含的函数发送,这意味着它无法直接访问渲染器。那么我如何将这些消息发送到渲染器。我假设这需要使用 ContextBridge 来完成,但我不知道如何成功地做到这一点,所以如果您的回复只是将我链接到上下文桥文档,请不要打扰,哈哈,我已经筋疲力尽了在那。我正在考虑的另一种选择是使用自定义事件,但我不确定这也能解决问题。

这是我尝试与 github 上的存储库一起执行的示例。如果您提出拉请求来修复存储库,我会很乐意合并并将存储库公开,以便其他人从中受益并与社区共享。https://github.com/JokerMartini/statusbar

作为一个小问题,我不确定为什么我不能再从未加载到渲染线程的 js 文件中调用“app”的 getPath 。

我从渲染器触发一个方法

索引.vue

const doWork = () => {
    window.messenger.doWork();
}
Run Code Online (Sandbox Code Playgroud)

电子预加载.js

import { contextBridge } from "electron";

const messenger = require("../src/helpers/messenger");
contextBridge.exposeInMainWorld("messenger", messenger);
Run Code Online (Sandbox Code Playgroud)

Messenger.js

const { app } = require("electron");
const path = require("path");

// using electron module to demonstrate this file can't be imported into renderer
export function showMessage(msg) {
  const dir = path.join(app.getPath("documents"), "presets");
  console.log(dir);
  // TODO: send message to renderer...
}

export function doWork() {
  console.log("Doing working...");

  // step 1: long process
  showMessage("Processing step 1...");

  // step 2: long process
  showMessage("Processing step 2...");

  // step 3: long process
  showMessage("Processing step 3...");
}
Run Code Online (Sandbox Code Playgroud)

我想显示从主发送到渲染器的消息,以显示在状态栏中

主.vue

<q-footer>
     <q-bar>
        <span class="text-caption">Show message here...</span>
    </q-bar>
</q-footer>
Run Code Online (Sandbox Code Playgroud)

** 更新 01 **

由于某种原因,渲染器没有收到我的消息。这是我的代码更改

电子预加载.js

import { contextBridge, ipcRenderer } from "electron";

contextBridge.exposeInMainWorld("electronAPI", {
  setStatus: (callback, func) =>
    ipcRenderer.on("set-status", (event, ...args) => func(...args)),
});
Run Code Online (Sandbox Code Playgroud)

索引.vue

<template>
  <q-page class="flex flex-center">
    <q-btn label="Show Message" @click="doWork" />
  </q-page>
</template>

<script>
import { defineComponent } from "vue";

export default defineComponent({

  setup() {
    // send message for testing...
    const doWork = () => {
      window.electronAPI.setStatus("sfsfsdfsd");
    };

    // recieve status messages...
    window.electronAPI.setStatus("set-status", (data) => {
      console.log("STATUS:", data);
      // TODO $store.dispatch("....");
    });

    return {
      doWork,
    };
  },
});
</script>
Run Code Online (Sandbox Code Playgroud)

mid*_*ing 6

对我有用的技术是使用preload.js脚本来定义具体的实现。相反,我使用preload.js脚本仅定义可以在主线程和渲染线程之间进行通信的通道(名称)。IE:分离你的关注点。在主线程脚本和渲染线程脚本中实现具体函数。


preload.js

// Import the necessary Electron components.
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;

// White-listed channels.
const ipc = {
    'render': {
        // From render to main.
        'send': [],
        // From main to render.
        'receive': [
            'message:update' // Here is your channel name
        ],
        // From render to main and back again.
        'sendReceive': []
    }
};

// Exposed protected methods in the render process.
contextBridge.exposeInMainWorld(
    // Allowed 'ipcRenderer' methods.
    'ipcRender', {
        // From render to main.
        send: (channel, args) => {
            let validChannels = ipc.render.send;
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, args);
            }
        },
        // From main to render.
        receive: (channel, listener) => {
            let validChannels = ipc.render.receive;
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender`.
                ipcRenderer.on(channel, (event, ...args) => listener(...args));
            }
        },
        // From render to main and back again.
        invoke: (channel, args) => {
            let validChannels = ipc.render.sendReceive;
            if (validChannels.includes(channel)) {
                return ipcRenderer.invoke(channel, args);
            }
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

注意:虽然我不使用Vue.js,但您应该了解以下两个文件的要点。

main.js(主线程)

const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;

const nodePath = require("path");

let window;

function createWindow() {
    const window = new electronBrowserWindow({
        x: 0,
        y: 0,
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true, 
            preload: nodePath.join(__dirname, 'preload.js')
        }
    });

    window.loadFile('index.html')
        .then(() => { window.show(); });

    return window;
}

electronApp.on('ready', () => {
    window = createWindow();
    
    // Send a message to the window.
    window.webContents.send('message:update', 'Doing work...');
});

electronApp.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        electronApp.quit();
    }
});

electronApp.on('activate', () => {
    if (electronBrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});
Run Code Online (Sandbox Code Playgroud)

index.html(渲染线程)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    
    <body>
        <span id="text-caption">Show message here...</span>
    </body>
    
    <script>      
        // Listen for message updates from the main thread.
        window.ipcRender.receive('message:update', (message) => {
            document.getElementById('text-caption').innerText = message;
        });
    </script>
</html>
Run Code Online (Sandbox Code Playgroud)