Search code examples
javascriptwindow.openwindow.location

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


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?


Solution

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