Refresh an open window that was opened with window.open when the url hash changes

7.8k views Asked by At

I open a small popup reference window using window.open(...) and give it a name. It is properly reused when subsequent window.opens are called for that window.

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");
}

The one case where it doesn't work properly is when someone has the window open at the help page url and only the hash changes (i.e. #jump-to-me). Only on a page reload does the page properly go to the hash.

Is there a way to find the open window, check that the URL matches what we're trying to open and conditionally do a window.location.refresh() when the hash changes?

3

There are 3 answers

0
Justin L. On BEST ANSWER

Was almost there, just needed to add an event listener on that particular window for the hashchange event.

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);
}
0
Gerrit Luimstra On

If I get this right, this will get you started.

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);

I hope this provides a good answer.

0
Bradley On

The browser doesn't reload the window if only material after the hash changes.

I found adding a random query parameter before the hash would force it to reload the underlying page:

function openHelp(hash) {
    const unique = /* generate a unique value or nonce somehow */;
    const helpWindow = window.open(location.protocol + "/help.aspx" + "?__uniq=" + unique + (hash ? "#" + hash : ""), "helpWindow", "width=750, height=600, resizable=1, scrollbars=1, location=0, directories=0, status=no, menubar=no, toolbar=no");
}

In my case, hash worked fine as the unique value. (It doesn't have to be "unique" in any sense, just as long as it changes when the hash does.)