【问题标题】:Electron App : Unable to load preload scriptElectron App:无法加载预加载脚本
【发布时间】:2021-06-18 17:01:09
【问题描述】:

每次启动电子应用程序时都会收到此错误。

electron/js2c/renderer_init.js:91 Unable to load preload script: C:\Users\Desktop\Projects\Electron-Apps\Electron\src\preload.js
(anonymous) @ electron/js2c/renderer_init.js:91
electron/js2c/renderer_init.js:91 Error: contextBridge API can only be used when contextIsolation is enabled

我的 preload.js 与我的 index.js 位于同一目录中,所以我在调试时有点不知所措。不知道为什么它不会加载我的 preload.js 文件。在我使用 eslint 将默认格式化程序设置为更漂亮之前,一切正常。

索引.js

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

Preload.js

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electron', {
  notificationAPI: {
    sendNotification(message) {
      ipcRenderer.send('notify', message);
    },
  },
  filesAPI: {
    sendEmails(content) {
      ipcRenderer.send('save-delete', content);
    },
  },
});

【问题讨论】:

    标签: javascript electron


    【解决方案1】:

    正如错误提示,需要启用contextIsolation 以允许您使用contextBridge API

    const createWindow = () => {
      // Create the browser window.
      const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          contextIsolation: true, // add this
          preload: path.join(__dirname, 'preload.js'),
        },
      });
    

    注意:contextIsolation 从 Electron 12.0 开始默认启用

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2019-10-21
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      相关资源
      最近更新 更多