Loading preload script in Electron and Vue

吃可爱长大的小学妹 提交于 2021-02-16 14:39:30

问题


I am using Vue CLI 3 and vue-cli-plugin-electron-builder to package my Vue Electron app and I am not able to get my preload.js script for electron working.

main window

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

preload.js

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

window.electron = {};
window.electron.dialog = dialog;

The window.electron.dialog is always undefined in my Vue component - the import is clearly not working. Note that window.electron is defined properly. I must be missing something.


回答1:


Add the following lines into the file vue.config.js , if the file does not exist create one in the root folder of your project

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

Check the documentation for more #preload-files




回答2:


The solution was more simple than expected. Imports work in window.onload event.

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

  window.electron = {};
  window.electron.dialog = dialog; // now set properly
};


来源:https://stackoverflow.com/questions/56478000/loading-preload-script-in-electron-and-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!