Mental Jetsam

By Peter Finch

Communicating between iframes and windows in Javascript

Posted by pcfinch on March 15, 2010

Sometimes it is not possible to keep your entire web application in one window, you may need to “pop-up” a new window or even embed an IFRAME containing another part of your application. If you need to communicate between the two windows the following code can be used in the “child” frames and windows to access Javascript functions in the parent window. Using this method it is possible to make the child window send notifications back to the parent window in order to update the parent windows state, etc. Note that this will only work when the windows and IFRAME’s come from the same domain.

In the parent window (main window) define any javascript functions as normal e.g in “index.html”.

tstFunction = function(message) {
  alert("Main Window " + message) ;
}

Include the following code in the child windows or IFRAMEs e.g. in “popup.html”.

function getParentFunction(funcName) {
  var func = null;
  // Child opened in new window e.g. target="blank"
  if (top.window.opener && !top.window.opener.closed) {
    try { func = eval("top.window.opener."+funcName); } catch (error) {}
  }
  if (!(func)) {
    // Child opened in IFRAME
    try { func = eval("top."+funcName); } catch (error) { }
  }
  if (!(func)) {
    throw new Error("function \""+funcName+"\" is not in parent window.");
  }
  return func; 
}

If you need to call a function defined in the parent window from the child do this.

var foo = getParentFunction("tstFunction") ;
foo("Hello from iframe") ;
Advertisements

4 Responses to “Communicating between iframes and windows in Javascript”

  1. Works nicely. Thank you.

  2. JA said

    I have been looking for something like this for 2 days. Finally got this url. Thanks a lot for the post.

  3. Murat said

    It’s not a good practice to use the evil eval. You could instead try top.window.opener[funcName] or use some alternative.

  4. Taren said

    Very energetic article, I liked that bit. Will there be a part 2?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: