我正在尝试设置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.jsconst { 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/