【问题标题】:Open a new window to display a html file using a menu click - Electron使用菜单单击打开一个新窗口以显示 html 文件 - Electron
【发布时间】:2017-02-04 19:53:51
【问题描述】:

我是 Electron 和 JavaScript 的新手。我正在构建一个电子应用程序。我知道如何通过单击本机菜单中的项目(通过研究文档)在浏览器中打开 URL,但我需要使用 Electron 的本机菜单单击在另一个 Electron 窗口中打开 html 文件。如果我的菜单结构如下所示,我该如何实现?请帮忙。

const {Menu} = require('electron');

const nativeMenus = [
    {
        label: 'About',
        submenu: [
            {
                label: 'About',
                click () {--- code to open about.html file in another electron window}
            }
        ]

    }
]

const menu = Menu.buildFromTemplate(nativeMenus);
Menu.setApplicationMenu(menu);

【问题讨论】:

标签: javascript node.js electron


【解决方案1】:

如果它全部在 main.js 中,只需创建一个函数来创建一个新窗口,然后在单击菜单项时调用它。

const { Menu } = require('electron')
const ipc = require('electron').ipcRenderer

const nativeMenus = [
  {
    label: 'About',
    submenu: [
      {
        label: 'About',
        click() {
          openAboutWindow()
        }
      }
    ]
  }
]

const menu = Menu.buildFromTemplate(nativeMenus)
Menu.setApplicationMenu(menu)

var newWindow = null

function openAboutWindow() {
  if (newWindow) {
    newWindow.focus()
    return
  }

  newWindow = new BrowserWindow({
    height: 185,
    resizable: false,
    width: 270,
    title: '',
    minimizable: false,
    fullscreenable: false
  })

  newWindow.loadURL('file://' + __dirname + '/views/about.html')

  newWindow.on('closed', function() {
    newWindow = null
  })
}

让我知道这是否适合你。

【讨论】:

  • 非常感谢。但我的菜单脚本也在 main.js 文件中。那么如何解析const变量ipc呢?
  • 在这种情况下更容易,我会更新 cod 以反映这一点。
【解决方案2】:

您将BrowserWindow 实例存储在一个变量中,为了回答这个问题,我假设它是win。 user7252292 确实为您提供了一个很好的答案。但是,如果您需要另一个窗口,那么您将不得不为相同的目的创建另一个函数。我将创建一个函数来创建modals。它们基本上是需要父窗口的窗口,并且在模式关闭之前您无法响应父窗口。

const createModal = (htmlFile, parentWindow, width, height) => {
  let modal = new BrowserWindow({
    width: width,
    height: height,
    modal: true,
    parent: parentWindow,
    webPreferences: {
      nodeIntegration: true
    }
  })

  modal.loadFile(htmlFile)

  return modal;

}

const {Menu} = require('electron');

const nativeMenus = [
  {
      label: 'About',
      submenu: [
          {
            label: 'About',
             click () {

              createModal("myfile.html",win,600,800); // Win is the browerwindow instance

            }
        }
    ]
  }
]

const menu = Menu.buildFromTemplate(nativeMenus);
Menu.setApplicationMenu(menu);

另外,您可以将 createModal 存储在变量中并修改模态,因为它返回模态本身。

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2015-08-25
    • 2019-04-22
    相关资源
    最近更新 更多