在 Electron 和 Vue 中加载预加载脚本



我正在使用 Vue CLI 3 和 vue-cli-plugin-electron-builder 来打包我的 Vue Electron 应用程序,但我无法获得我的预加载.js 电子工作脚本。

主窗口

win = new BrowserWindow({
  width: 800,
  height: 600
  webPreferences: {
    nodeIntegration: false,
    preload: path.join(__dirname, "/../src/preload.js") // works but window.electron.dialog in undefined
  }
});

预载.js

const { dialog } = require("electron");
window.electron = {};
window.electron.dialog = dialog;

window.electron.dialog在我的 Vue 组件中始终未定义 - 导入显然不起作用。请注意,window.electron定义正确。我一定错过了什么。

将以下行添加到文件vue.config.js中,如果该文件不存在,请在项目的根文件夹中创建一个

module.exports = {
 //...
 pluginOptions: {
  electronBuilder: {
    preload: 'src/preload.js',
    // Or, for multiple preload files:
    // preload: { preload: 'src/preload.js', otherPreload: 'src/preload2.js' }
  }
 }
 //...
}

查看文档以获取更多 #preload 文件

解决方案比预期的要简单。导入在window.onload事件中起作用。

window.onload = () => {
  const { dialog } = require("electron").remote;
  window.electron = {};
  window.electron.dialog = dialog; // now set properly
};

最新更新