When a page is running inside of an iframe, the parent object is different than the window object. You can still access parent from within an iframe even though you can't access anything useful on it. This code will never cause an error even when crossing origins.
Communicating directly between iframes is also possible by combining window. parent with target as defined above. In conclusion, the postMessage method is a more dynamic alternative to the single DOM, better suited if you load multiple pages in one iframe, but not always easier and it still requires the use of the DOM.
With different domains, it is not possible to call methods or access the iframe's content document directly.
You have to use cross-document messaging.
For example in the top window:
myIframe.contentWindow.postMessage('hello', '*');
and in the iframe:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
For example in the top window:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
and in the iframe:
window.top.postMessage('hello', '*')
In 2018 and modern browsers you can send a custom event from iframe to parent window.
iframe:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
parent:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
PS: Of course, you can send events in opposite direction same way.
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
This library supports HTML5 postMessage and legacy browsers with resize+hash https://github.com/ternarylabs/porthole
Edit: Now in 2014, IE6/7 usage is quite low, IE8 and above all support postMessage
so I now suggest to just use that.
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
Use event.source.window.postMessage
to send back to sender.
From Iframe
window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
if (event.data === 'GOT_YOU_IFRAME') {
console.log('Parent received successfully.')
}
}
Then from parent say back.
window.onmessage = (event) => {
event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}
the window.top
property should be able to give what you need.
E.g.
alert(top.location.href)
See http://cross-browser.com/talk/inter-frame_comm.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With