

Say I want to click a button on the parent page, and have that do something inside the iframe.
#JAVASCRIPT IFRAME CODE#
Some of these answers don't address the CORS issue, or don't make it obvious where you place the code snippets to make the communication possible. This script first checks the domain is the expected domain, and then looks at the message, which it either displays to the user, or responds to by sending a message back to the document which sent the message in the first place. For example, the script in document B might look like: window.addEventListener('message', receiver, false) To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). O.contentWindow.postMessage('Hello world', '') The script in document A might look like: var o = document.getElementsByTagName('iframe') If the iFrame's target and the containing document are on a different domain, the methods previously posted might not work, but there is a solution:įor example, if document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A.

a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent script when it has finished loaded and is ready to be called back. It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. if you know you only have the one iframe on the page. ames is also very reliable, but knowing the right index is the trick. ( id="." would be better but IE doesn't like that.) But you then have to use a name="." attribute to be able to get a frame by name, which is slightly ugly/ deprecated/transitional. ames returning the window is the oldest and hence most reliable interface. Even so, the standard doesn't explicitly say that you get the window object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care. You can also try, which a couple of older browsers allow but IE doesn't. This is because the DOM Level 1 HTML standard has nothing to say about the window object. ntentWindow is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. There are some quirks to be aware of here.
