Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue/Electron IPC between main and renderer

I'm trying to setup communication between my Vue browser app and the electron main process, but it is not working.

Before startBot() is even called, I get an error message that __Dirname is unknown. But this constant is nowhere in to be found in the code.

What am I doing wrong?

https://gist.github.com/Quenos/7d6dbe4f5410739499ea9e3b0b4f961a.js

This is the background.js where I open the browser window with a preload. This has the purpose of making window available to the browser process

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"),
    },
  });

This is said 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));
    }
  },
});

The main process which contains listeners that then will do file handling

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" });
});

And the browser process which send requests to do file handling:

async startBot() {
  window.ipc.send("OPEN_FILE", { path: "./HH_trdr_bot.csv" });
}
like image 612
MPL Avatar asked Sep 06 '25 03:09

MPL


1 Answers

In the meantime I've found this article that perfectly answers my question

https://medium.com/swlh/how-to-safely-set-up-an-electron-app-with-vue-and-webpack-556fb491b83

like image 198
MPL Avatar answered Sep 08 '25 00:09

MPL