【问题标题】:Electron: Cannot read property 'send' of undefined电子:无法读取未定义的属性“发送”
【发布时间】:2019-05-05 17:03:31
【问题描述】:

我正在尝试使用 fs 模块从目录中读取文件,并在 Electron 应用程序中以 id displayfiles 将其显示在 div 中。我不断收到错误:

 Cannot read property 'send' of undefined

这是我的 renderer.js

// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const electron = require('electron');
const dialog = electron.dialog;
const fs = require('fs');
const remote = require ("electron").remote;
const ipcRenderer = electron.ipcRenderer;
const template=[
    {
        label: 'File',
        submenu: [
            {
                label:'Open USB',
                click () { dialog.showOpenDialog( {
                    properties: ['openDirectory']
                },directorySelectorCallback)

                }
            },
            {
                label:'Exit',
                click() {

                }
            },
        ]
    },
    {
        label: 'Edit',
        submenu: [
            {role: 'undo'},
            {role: 'redo'},
            {type: 'separator'},
            {role: 'cut'},
            {role: 'copy'},
            {role: 'paste'},
            {role: 'pasteandmatchstyle'},
            {role: 'delete'},
            {role: 'selectall'}
        ]
    },
    {
        label: 'View',
        submenu: [
            {role: 'reload'},
            {role: 'forcereload'},
            {role: 'toggledevtools'},
            {type: 'separator'},
            {role: 'resetzoom'},
            {role: 'zoomin'},
            {role: 'zoomout'},
            {type: 'separator'},
            {role: 'togglefullscreen'}
        ]
    },
    {
        role: 'window',
        submenu: [
            {role: 'minimize'},
            {role: 'close'}
        ]
    },
]

function directorySelectorCallback(filenames) {
    if (filenames && filenames.length > 0) {
        console.log(filenames[0]);
        fs.readdir(filenames[0], (err, files) => {
            'use strict';
            if (err) throw  err;
            //the files parameter is an array of the files and folders in the path we passed. So we loop through the array, printing each file and folder
            for (let file of files) {
                console.log(file);
                ipcRenderer.send('add-file', 'an-document.getElementById(\'display-files\').innerHTML += `<li>${file}</li>`;')

            }
        });
    }
}
module.exports.template=template;

这是我的 main.js 代码:

// Modules to control application life and create native browser window
const electron = require('electron')
const {app, BrowserWindow,Menu,ipcMain} = require('electron')
const menuTemplate=require('./renderer.js').template
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow=null;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/Rexnord.ico'})

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
   mainWindow.webContents.openDevTools()
  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
    let menu = Menu.buildFromTemplate(menuTemplate)
    Menu.setApplicationMenu(menu);
}
ipcMain.on('add-file', (event, arg)=> {
   mainWindow.webContents.executeJavaScript(arg);
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

我试图通过 ipc 模块在 renderer.js 和 main.js 文件之间进行通信。根据我阅读的内容,我应该能够 ipcrenderer 模块通过通道向主进程发送消息,但我一直收到此错误。谁能告诉我我做错了什么?

【问题讨论】:

  • 你可以尝试只发送一个虚拟字符串而不是一些 Javascript 来运行吗?比如foobar 什么的。
  • 您最好只发布最少的代码,这是重现实际问题所必需的。 see ;)

标签: node.js electron


【解决方案1】:

你的问题是你 require(./renderer) 来自 Main 进程。

  • 这是必要的,因为Menu 是一个 进程模块
  • OTOH ipcRenderer 未在 Main 进程中定义,因此在回调中也不可用

您应该重新构造您的代码,以使用 Main 和 Renderer 中的renderer.js both

由于您向 Main 发送消息只是为了在 Renderer 中执行代码,因此您可以简单地在 ipcRenderer 上设置一个侦听器来操作 DOM 并在 Main 进程中执行其他所有操作(clickarguments 使这变得容易)。

main.js

const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')
const { menuTemplate } = require('./template')

app.once('ready', () => {
  let win = new BrowserWindow()
  win.loadURL(path.join(__dirname, '/index.html'))

  let menu = Menu.buildFromTemplate(menuTemplate)
  Menu.setApplicationMenu(menu)
})

template.js

const { dialog } = require('electron')
const fs = require('fs')

module.exports = {
  menuTemplate: [
    {
      label: 'File',
      submenu: [
        {
          label: 'Open USB',
          click (menuItem, browserWindow, event) {
            dialog.showOpenDialog({
              properties: ['openDirectory']
            }, ([dir]) => {
              try {
                if (fs.statSync(dir).isDirectory()) {
                  const files = fs.readdirSync(dir)
                  browserWindow.webContents.send('add-file', files)
                }
              } catch (err) {
                console.error(err)
              }
            })
          }
        }
      ]
    }
  ]
}

index.html

<html>
  <body>
    <script>
      const { ipcRenderer } = require('electron')
      ipcRenderer.on('add-file', (event, files) => {
        files.forEach(f => {
          document.getElementById('display-files').innerHTML +=
            `<li>${f}</li>`
        })
      })
    </script>
    <div id='display-files'>
      Files:
    </div>
  </body>
</html>

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2021-04-16
    相关资源
    最近更新 更多