node.js - 主渲染器之间的Vue/Electron IPC

标签 node.js vue.js electron

我正在尝试设置Vue浏览器应用程序与 Electron 主进程之间的通信,但是它不起作用。
在甚至调用startBot()之前,我收到一条错误消息,说明__Dirname是未知的。但是在代码中找不到此常量。
我究竟做错了什么?
https://gist.github.com/Quenos/7d6dbe4f5410739499ea9e3b0b4f961a.js
这是background.js,我在其中预加载打开了浏览器窗口。这样做的目的是使窗口可用于浏览器进程

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1300,
    height: 1100,
    title: "Hedgehog TRDR Bot",
    icon: path.join(__static, "hedgehog.jpg"),
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
      // __static is set by webpack and will point to the public directory
      preload: path.resolve(__static, "preload.js"),
    },
  });
这就是说preload.js
const { contextBridge, ipcRenderer } = require("electron");

const validChannels = ["READ_FILE", "WRITE_FILE"];
contextBridge.exposeInMainWorld("ipc", {
  send: (channel, data) => {
    if (validChannels.includes(channel)) {
      ipcRenderer.send(channel, data);
    }
  },
  on: (channel, func) => {
    if (validChannels.includes(channel)) {
      // Strip event as it includes `sender` and is a security risk
      ipcRenderer.on(channel, (event, ...args) => func(...args));
    }
  },
});
包含监听器的主要过程,然后将进行文件处理
const { ipcMain } = require("electron");
const fs = require("fs");
var file;

ipcMain.on("OPEN_FILE", (event, payload) => {
  console.log("daaro");
  file = fs.createWriteStream(payload.path);
  event.reply("OPEN_FILE", { content: "roger" });
});

ipcMain.on("TEST_FILE", (event, payload) => {
  console.log("daaro");
  file.write(payload.path);
  event.reply("OPEN_FILE", { content: "roger" });
});
发送请求进行文件处理的浏览器进程:
async startBot() {
  window.ipc.send("OPEN_FILE", { path: "./HH_trdr_bot.csv" });
}

最佳答案

同时,我发现这篇文章可以完美回答我的问题
https://medium.com/swlh/how-to-safely-set-up-an-electron-app-with-vue-and-webpack-556fb491b83

关于node.js - 主渲染器之间的Vue/Electron IPC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66120540/

相关文章:

node.js - NPM - 无法安装 socket.IO

javascript - 登录/注销后 Vuex 状态不会改变

javascript - Electron 变焦级别更改事件

electron - 具有SDL的macOS上的 Electron 优先级高DPI支持

node.js - $node --debug 和 $nodedebug 之间的区别

node.js - 如何在一个 VPS 上托管具有 3 个不同域的 3 个 Node 应用程序?

javascript - 如何仅在 spa 需要时才包含 vue 组件?

javascript - Electron 无框窗口。使用默认菜单栏打开

javascript - 初学者在这里。我需要帮助更好地理解这个回调函数

vue.js - @vue/test-utils 未知的自定义元素 : <router-view>