当网址哈希值发生变化时,刷新一个用window.open打开的打开窗口

时间:2016-12-22 22:32:09

标签: javascript window.open window.location

我使用window.open(...)打开一个小弹出参考窗口,并给它起一个名字。当为该窗口调用后续window.open时,它会被正确地重用。

function openHelp(hash) {
    var helpWindow = window.open(location.protocol + "/help.aspx" + (hash ? "#" + hash : ""), "helpWindow", "width=750, height=600, resizable=1, scrollbars=1, location=0, directories=0, status=no, menubar=no, toolbar=no");
}

无法正常工作的一种情况是,有人在帮助页面网址处打开了窗口,只有哈希值发生变化(即#jump-to-me)。只有在页面重新加载时,页面才能正确地转到哈希。

有没有办法找到打开的窗口,检查网址是否与我们尝试打开的内容相匹配,并在哈希更改时有条件地执行window.location.refresh()

2 个答案:

答案 0 :(得分:1)

如果我做对了,这会让你开始。

var extraWindow;

function makeWindow(){
   extraWindow= window.open(/* .. */);
}

// this will reload the extra window that you just opened.
function reloadWindow(){
  if(extraWindow){
     extraWindow.location.reload();
  }
}

makeWindow();

// reload the window when the hash changes or possibly change the page url based on this.
window.addEventListener("hashchange", reloadWindow, false);

我希望这能提供一个好的答案。

答案 1 :(得分:0)

几乎就在那里,只需要在hashchange事件的特定窗口上添加一个事件监听器。

function openHelp(hash) {
    var helpWindow = window.open(location.protocol + "/help.aspx" + (hash ? "#" + hash : ""), "helpWindow", "width=750, height=600, resizable=1, scrollbars=1, location=0, directories=0, status=no, menubar=no, toolbar=no");
    helpWindow.addEventListener("hashchange", function () { this.location.reload() }, false);
}
相关问题