学无先后,达者为师

网站首页 Vue 正文

解决vue3 + electron 中使用ipcRenderer报错的问题

作者:九段刀客 更新时间: 2022-04-22 Vue

版本信息

  • “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);

原文链接:https://jddke.blog.csdn.net/article/details/122798203

栏目分类
最近更新