user7776690
user7776690

Reputation:

Javascript Electron Menu open app window from Menu template file

In my Electron App, I can created a Menu template at an external local file and called it menuTemplate.js

The menu works find but I want to be able to open a local file from it, for example about.html

I've tried 'window.open('url here')' but it doesn't understand window ...

Here is the template:

module.exports = [
  {
    label: 'Electron',
    submenu: [
      {label: 'Item 1'},
      {label: 'Item 2'}
    ]
  },
  {
    label: 'Actions',
    submenu: [
      {label: 'Action 1'},
      {label: 'Action 2'},
      {label: 'Action 3'},
      {role: 'toggledevtools'},
      {label: 'ClickMe', click () { window.open('url here'); } }
    ]
  }
]

I've tried shell.openExternal and it works but I cannot get an app window to open from here.

How can I do this?

Upvotes: 1

Views: 2186

Answers (2)

Henry Romero
Henry Romero

Reputation: 11

This is what worked for me:

    label: 'General',
    submenu: [
      {label: 'Unidades',          
      click () {   mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, './app/fixed_footer.html'),
        protocol: 'file:',
        slashes: true

      })); }

Upvotes: 1

user5733510
user5733510

Reputation:

While it is a good idea to separate a template like this into a separate file, you cannot access the scope of the original file there. To solve this problem you have to bring your window from your mainfile (assumed to be called main.js) into your menuTemplate.js.

You could do this for example by creating a method that builds the template on execution. It could look something like this:

menuTemplate.js

module.exports = function(window){
    return [
      {
        label: 'Electron',
        submenu: [
          {label: 'Item 1'},
          {label: 'Item 2'}
        ]
      },
      {
        label: 'Actions',
        submenu: [
          {label: 'Action 1'},
          {label: 'Action 2'},
          {label: 'Action 3'},
          {role: 'toggledevtools'},
          {label: 'ClickMe', click () { window.open('url here'); } }
        ]
      }
    ]
}

Now when loading the template in main.js you do not do something like

const template = require('menuTemplate')

but something like

const template = require('menuTemplate')(window),

with "window" being the name of your window variable.

Upvotes: 3

Related Questions