解决vue3 + electron 中使用ipcRenderer报错的问题_九段刀客的博客-CSDN博客

版本信息

  • “electron”: “^13.0.0”,
  • “vue”: “^3.2.19”

报错原因

electron新版本默认禁止页面中直接操作 electron的相关api

解决办法

通过脚本注入webview中,将要操作的api添加到全局变量中

1、vue.config.js

module.exports = {
  pluginOptions: {
    electronBuilder: {
      preload: "src/preload.js"
    }
  }
};

2、preload.js (和main.js同级需要新建)

import { contextBridge, ipcRenderer } from "electron";

contextBridge.exposeInMainWorld("electron", {
  ipcRenderer,
});

3、background.js中添加

preload: path.join(__dirname, “preload.js”) 添加导入即可
import path from "path";

 const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, "preload.js")
    }
  });

4、使用

window.electron.ipcRenderer.send("test")

主线程中如果有事件需要到渲染线程中响应,需要在这里做转接

preload.js

import { contextBridge, ipcRenderer } from "electron";

contextBridge.exposeInMainWorld("electron", {
  ipcRenderer,
});

.vue文件中的接收

window.electron.onMessage((val) => {
      console.log(val, "=====");
});

主线程background.js中的发起,win为 let win = new BrowserWindow({})

win.webContents.send("message", text);

原网址: 访问
创建于: 2023-11-02 11:19:48
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论