Call JavaScript of parent window from child window

David Bélanger picture David Bélanger · Jun 13, 2013 · Viewed 18.2k times · Source

I have a calendar and when I click on a <td>, a pop-up window appears so you can create your evenement for the date you selected. I want to add a feature.

When the user finishes creating the event, I want to send a JavaScript request to the parent page so I can refresh the calendar using AJAX. Basically, I want to call a function from the child, but the function is on the parent page.

On Google, I only found a script that can refresh the parent window – nothing about a “parent callback”. ☹ Is it even possible?

P.S. The answer can be pure JS or jQuery, it doesn’t matter. I’ll keep looking in the meanwhile.

Answer

Michael Geary picture Michael Geary · Jun 13, 2013

What you're looking for is a reference to the window that opened the popup window. Once you have that, you can call functions in that window, read and write variables in that window, or even manipulate its DOM.

That reference is called opener. It gives you the window object for the window that opened the current window. For example, if you have a function in the original window like this:

function updateMe( data ) {
    alert( data );
}

then in the popup window you could call it like this:

opener.updateMe( 'Hello!' );

Naturally, you need to make sure that updateMe() is a global function in the original page. Or if you have some object in the original page and updateMe() is a method of that object, you can still do it, as long as the object is global. e.g. in the host page:

var myObject = {
    updateMe: function( data ) {
        alert( data );
    }
};

then in the popup you could do:

opener.myObject.updateMe( 'Hello!' );

Basically, as long as you could get to the object or function in the original page with window.whatever, then in the popup you can simply change that to opener.whatever.