首页 > 解决方案 > 在子渲染器 electronjs 中访问节点失败

问题描述

打开子窗口时,我收到一条错误消息“未捕获的 ReferenceError:未定义要求”。我正在向主进程使用异步消息,以便在从主渲染器脚本按下按钮时为主应用程序窗口创建一个子窗口。我可以访问主渲染器脚本中的节点。我想在子窗口的脚本中添加一些节点库,但我遇到了 nodeIntegration 问题。我在主渲染和子渲染上将其设置为 true。我可以在脚本中访问主要 html 渲染的节点功能,但不能访问子节点功能。我想我可能为电子应用程序构建了不正确的东西。以下是相关代码:

index.js(发送消息的主渲染器脚本,在按下按钮时调用)

function addImage(){
    ipcRenderer.send('add-image-req', 'testID');
}

main.js 片段

function createWindow () {
  const win = new BrowserWindow({
    width: 1200,
    height: 900,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInSubFrames: true,
      nodeIntegrationInWorker: true,
      contextIsolation: false,
      enableRemoteModule: true
      //preload: path.join(__dirname, 'preload.js')
    }
  })

  win.loadFile('./assets/html/index.html')
  win.webContents.openDevTools()

  /*
  var menu = Menu.buildFromTemplate([
      {
          label : 'File',
          submenu : [
              {
                  label : "Exit",
                  click() {
                      app.quit()
                  }
              }
          ]
      }
  ])

  Menu.setApplicationMenu(menu)
  */
  Menu.setApplicationMenu(null)

  ipcMain.on("add-image-req", (event, arg) => {
    console.log(arg);
    const child = new BrowserWindow({
      parent: win,
      nodeIntegration: true,
      contextIsolation: false                             
    })
  
  
    child.loadFile("./assets/html/image.html")
    child.webContents.openDevTools()
  })
}

image.js(image.html 页面的脚本,子)

const path = require("path");

如果我的结构完全不正确,请告诉我。

以最小的可重复性进行编辑

为项目创建一个新文件夹并在终端中执行

npm init -y
npm install electron

然后制作以下5个文件:

  1. main.js
  2. 索引.html
  3. index.js
  4. 图像.html
  5. 图像.js

进入创建的 package.json 并将“main”键更改为“main.js”。将“脚本”键更改为“开始”:“电子。”。

以下是每个脚本应包含的内容。我会放最少的代码来重现它们。

主.js:

const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const path = require('path')


function createWindow () {
  const win = new BrowserWindow({
    width: 1200,
    height: 900,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInSubFrames: true,
      nodeIntegrationInWorker: true,
      contextIsolation: false,
      enableRemoteModule: true
      //preload: path.join(__dirname, 'preload.js')
    }
  })

  win.loadFile('./index.html')
  win.webContents.openDevTools()

  /*
  var menu = Menu.buildFromTemplate([
      {
          label : 'File',
          submenu : [
              {
                  label : "Exit",
                  click() {
                      app.quit()
                  }
              }
          ]
      }
  ])

  Menu.setApplicationMenu(menu)
  */
  Menu.setApplicationMenu(null)

  ipcMain.on("add-image-req", (event, arg) => {
    console.log(arg);
    const child = new BrowserWindow({
      parent: win,
      nodeIntegration: true,
      contextIsolation: false                             
    })
  
  
    child.loadFile("./image.html")
    child.webContents.openDevTools()
  })
}

app.whenReady().then(() => {
  createWindow()

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

索引.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    <button>Click</button>
    <script src="./index.js"></script>
</body>
</html>

index.js:

const { ipcRenderer } = require('electron')

document.querySelector("button").addEventListener('click', () => {
    ipcRenderer.send('add-image-req', 'testID')
})

图片.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <a href="">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eligendi adipisci impedit voluptatibus numquam consectetur sapiente possimus earum nobis et, molestiae minus ipsam. Dolore doloremque quia et assumenda maiores? Numquam, nostrum.</a>
    <script src="./image.js"></script>
</body>
</html>

图像.js:

const path = require("path");

然后尝试使用 npm start 运行,单击按钮时应该会出现错误。

标签: javascriptnode.jselectron

解决方案


nodeIntegration是一个子选项,webPreferences需要这样设置:

const child = new BrowserWindow({
  parent: win,
  webPreferences:  { // <- You need to add this option.
    nodeIntegration: true,
    contextIsolation: false
  }
})

nodeIntegration并且contextIsolation应该设置在webPreferences.


推荐阅读