电子:无法从另一个.js文件访问main.js

时间:2019-06-29 01:38:01

标签: node.js electron

我所有的html处理程序都放在第二个文件(b.js)中。他们看起来像这样:

window.onload = function () {
  let btn = window.getElementById('btn');
  button.addEventListener('click', fn);
}

这工作正常,但是我想创建一个按钮来打开另一个窗口,所以我尝试在main.js中添加导出的方法。我完整的main.js如下:

const {app, BrowserWindow} = require('electron');
let mainWindow;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 500,
    height: 300,
    frame: false,
    transparent: true,
    resizable: false,
    webPreferences: {
      nodeIntegration: true,
    }
  });
  mainWindow.setResizable(false);
  mainWindow.loadFile('index.html');
  mainWindow.webContents.openDevTools();

  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.quit();
  })
}

app.on('ready', createWindow);

module.exports = {
  openMainScreen: function () {
    mainWindow.loadFile("mainScreen.html");
    mainWindow.resizeTo(1200, 800);
  }
};

如果我按照自己的想法尝试在require(main.js)b.js:我会收到此错误:

Uncaught TypeError: Cannot read property 'on' of undefined

指向app.on('ready'...。看这篇文章:Cannot read property 'on' of undefined in electron javascript它说该应用程序启动了两次。我该如何解决?

1 个答案:

答案 0 :(得分:0)

我解决此问题的方法是使用IPCmain中内置的电子在html呈现的javascript和运行该应用程序的主要javascript之间进行通信。
https://electronjs.org/docs/api/ipc-main

相关问题