首页 > 解决方案 > nwjs 菜单在 window.location.href 更改后停止工作

问题描述

导航到另一个网址后,菜单停止工作。现在我添加了菜单:

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

我创建了一个 github 分支来显示这个问题: https ://github.com/wvary/nwjs-firewall-test/tree/tested-menu

以下是重现此问题的方法:

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

应用程序启动后,单击 Google 菜单项以浏览 Google 网站。然后点击 Github 菜单项。它应该在 Github 上冲浪,但事实并非如此。

标签: menuwindowreloadnwjs

解决方案


您需要创建一个占据整个页面并显示它的 iframe,并将其 src 属性设置为您要访问的 url。

编辑:您需要使用 webview 而不是 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

推荐阅读