【问题标题】:Electron: can't access main.js from another .js fileElectron:无法从另一个 .js 文件访问 main.js
【发布时间】:2019-11-10 20:41:25
【问题描述】:

我将所有的 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)in b.js:我收到此错误:

Uncaught TypeError: Cannot read property 'on' of undefined

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

【问题讨论】:

  • 为什么b.js 需要要求main.js?当您需要时,它将调用所有代码..您还必须将默认代码包装在一个导出方法中,然后您可以控制从 b.js 调用它,但是 b.js 也可以成为 main.js :/
  • 为什么不用api呢? electronjs.org/docs/api/window-open
  • @LawrenceCherone b.js 需要 main.js 的原因是我需要访问“mainWindow”来更新它的大小并加载一个新的 html 文件来显示。

标签: node.js electron


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 2015-07-04
    • 2020-08-25
    • 1970-01-01
    • 2015-05-17
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    相关资源
    最近更新 更多