refresh child window from parent window

When opening your child window from the parent, remember the return value in a variable somewhere:

var childWindow = window.open(/* ... */);

...and when you want to refresh the child:

childWindow.location.reload();

Note that some browsers will prevent access to childWindow.location.reload if the parent and child aren't loaded from the same origin.

Here's a quick-and-dirty example (live copy — note: the live copy only works in non-edit mode, like the link given, because otherwise JSBin uses null.jsbin.com instead of output.jsbin.com and so the origin doesn't match):

HTML:

<input type='button' id='btnOpen' value='Open Child'>
<input type='button' id='btnClose' value='Close Child'>
<input type='button' id='btnRefresh' value='Refresh Child'>

JavaScript:

(function() {
    var childWindow;

    document.getElementById('btnOpen').onclick = openChildWindow;
    document.getElementById('btnClose').onclick = closeChildWindow;
    document.getElementById('btnRefresh').onclick = refreshChildWindow;

    function openChildWindow() {
        if (childWindow) {
            alert("We already have one open.");
        } else {
            childWindow = window.open(location.protocol + "//" + location.host + "/cotokijigu/1");
        }
    }

    function closeChildWindow() {
        if (!childWindow) {
            alert("There is no child window open.");
        }
        else {
            childWindow.close();
            childWindow = undefined;
        }
    }

    function refreshChildWindow() {
        if (!childWindow) {
            alert("There is no child window open.");
        } else {
            childWindow.location.reload();
        }
    }
})();

Caveat: I would never recommend hooking up event handlers with onclick properties as above. Instead, I'd use addEventListener (on standards-based browsers) or attachEvent (on IE), by using a library or a utility function like this one. Used the properties above to avoid obscuring the main point.

Tags:

Javascript