Search code examples
menuwindowreloadnwjs

nwjs menu stop working after window.location.href changed


The menu stop working after I navigate to another url. Here's now I added the menu:

var menu = new nw.Menu({
  type: 'menubar'
});
var menuItems = new nw.Menu();

menuItems.append(
  new nw.MenuItem({
    label: 'Surf Google',
    click: function() {
      window.location.href = 'https://google.com';
    }
  })
);

menuItems.append(
  new nw.MenuItem({
    label: 'Surf Github',
    click: function() {
      window.location.href = 'https://github.com';
    }
  })
);

menu.append(
  new nw.MenuItem({
    label: "The Menu",
    submenu: menuItems
  })
);

var w = nw.Window.get();

w.menu = menu

I've created a github branch to show this issue: https://github.com/wvary/nwjs-firewall-test/tree/tested-menu

Here's how to reproduce this issue:

git clone https://github.com/wvary/nwjs-firewall-test.git
cd nwjs-firewall-test
git checkout tested-menu
npm run build
./dist/nwjs-firewall-test-1.0.0-mac-x64/nwjs-firewall-test.app/Contents/MacOS/nwjs

After the app launches, click on the Google menu item to surf the Google website. Then click on the Github menu item. It should surf Github, but it doesn't.


Solution

  • You need to create an iframe which takes up the whole page and show it and set it's src attribute to the url you want to go to.

    EDIT: you need to use a webview instead of an iframe

    HTML:

    <webview style="display:none; position:fixed; width: 100%; height:100%; bottom:0; right:0; top:0; left:0;" id="view_iframe"></webview>
    

    JS:

    var menu = new nw.Menu({
      type: 'menubar'
    });
    var menuItems = new nw.Menu();
    
    menuItems.append(
      new nw.MenuItem({
        label: 'Surf Google',
        click: function() {
          document.getElementById("view_iframe").style.display = "block";
          document.getElementById("view_iframe").src = "https://google.com";
        }
      })
    );
    
    menuItems.append(
      new nw.MenuItem({
        label: 'Surf Github',
        click: function() {
          document.getElementById("view_iframe").style.display = "block";
          document.getElementById("view_iframe").src = "https://github.com";
        }
      })
    );
    
    menu.append(
      new nw.MenuItem({
        label: "The Menu",
        submenu: menuItems
      })
    );
    
    var w = nw.Window.get();
    
    w.menu = menu