【问题标题】:Uncaught ReferenceError: require is not defined in Electron BrowserWindow未捕获的 ReferenceError:Electron BrowserWindow 中未定义要求
【发布时间】:2021-08-16 05:01:51
【问题描述】:

我是electron js 的新手,我正在尝试使用devtron。当我在电子浏览器窗口中使用require 时。我面临这个错误

Uncaught ReferenceError: require is not defined

请注意,在 BrowserWindow 中使用 require 时出现此错误,而不是在代码中。我还尝试在webPreferences 中设置nodeIntegration: true,contextIsolation: true。我已附上截图。

这是我的 main.js 代码

const {app, BrowserWindow} = require('electron')
const path = require('path')
require('electron-reload')(__dirname);



function createWindow () {
  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 700,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: true
    }
  })
  mainWindow.loadFile('index.html')
 }

app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
});

【问题讨论】:

标签: javascript node.js electron


【解决方案1】:

contextIsolation 已启用,禁用 contextIsolationnodeIntegration 应该可以工作。

webPreferences: {
  nodeIntegration: true,
  contextIsolation: false
}

【讨论】:

  • 但是,为了安全起见,建议使用contextIsolation 而不是nodeIntegrationnodeIntegration 将整个节点 API 暴露给渲染器,这是有潜在危险的。确保仅在将加载受信任的非外部内容的窗口上启用 nodeIntegration
  • 感谢您的回答。你能解释一下这两件事吗?或分享我可以从中了解这些的任何链接?
  • nodeIntegration 允许您在渲染器进程中使用require(),如果您加载外部页面,例如example.com,并在该窗口中启用nodeIntegration,则网页可以使用require ,允许它访问文件系统 API const fs = require('fs') 和其他节点 API。这通常可以通过不加载外部页面来防止,但最好使用contextIsolation,因为它允许您选择渲染器进程可以执行哪些 API/函数。下面是一个如何实现contextIsolation的例子:stackoverflow.com/questions/59993468
猜你喜欢
  • 1970-01-01
  • 2020-05-16
  • 2012-12-16
  • 2017-02-28
  • 2017-06-01
  • 2018-01-30
  • 2019-09-28
  • 1970-01-01
相关资源
最近更新 更多