0

I have an HTML frame that I created by running window.open('/a-new-page/', 'my-second-frame'); in the parent page.

When a button is clicked in the frame, I want to trigger a function on the parent page. (In my particular situation, the function updates some of the parent frames HTML)

What is the simplest way to do this?

Both the parent and the frame have the same domain.

Don P
  • 60,113
  • 114
  • 300
  • 432

1 Answers1

1

By using the window.parent keyword from within your iframe you can gain access to elements in the parent window if the iframe and the parent window is on the same domain.

Try something like window.parent.yourParentWindowFunctionName() to call a function in the parent window.

Jako Basson
  • 1,461
  • 12
  • 19
  • Interesting, when I tried running parent.helloWorld() in my frame, it printed out my hello world message in my frame's console... not the parents. Will test again. – Don P May 19 '15 at 08:11
  • This, or, if he's using anonymous functions, in order to access the child context you can use `document.getElementById('my-second-frame').contentWindow.document` – Jack May 19 '15 at 08:11
  • Yeah I just tested it, and calling `parent.myFunction()` executes the parent's function in the frame that called it. I tested it with `console.log()` - and the message showed up in my frame's console. Then I tested it with the function as `$('div').html('HI!');` which also replaces the div's content in my frame, not the parent. – Don P May 19 '15 at 08:14
  • Yes, if the call parent.helloWorld() did not return undefined then it called the function helloWorld() in your parent window. Do you mean your browser console when saying that it printed in your frame's console? If so then the console window picks up any console.log regardless of it coming from the parent or iframe. – Jako Basson May 19 '15 at 08:16
  • Try parent.$('div').html('HI!'); instead to change content in the parent. As with the console.log, see my previous comment. – Jako Basson May 19 '15 at 08:17
  • Hm, `parent.$('div').html('HI!');` still changes the div content in the frame, not the parent – Don P May 19 '15 at 08:26
  • Here's a comprehensive answer on this subject using jquery: http://stackoverflow.com/questions/18372746/targeting-the-parent-window-using-jquery – Jako Basson May 19 '15 at 08:41
  • Wow - changing it to "opener.helloWorld()` works. Interesting that it's different from `parent.helloWorld()`. – Don P May 19 '15 at 08:47