Problem
The iframe’s website isn’t on the same domain as the parent site, but they’re both mine, and I’d like to interact between the two. Is that even possible?
Asked by Danny Fox
Solution #1
It is not possible to call methods or access the iframe’s content document directly while using separate domains.
Cross-document messaging is required.
In the top window, for example:
myIframe.contentWindow.postMessage('hello', '*');
as well as in the iframe:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
In the top window, for example:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
as well as in the iframe:
window.top.postMessage('hello', '*')
Answered by user123444555621
Solution #2
You can send a custom event from an iframe to the parent window in 2018 and contemporary browsers.
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: You can, of course, send events in the reverse direction in the same way.
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
Answered by Stranger in the Q
Solution #3
This library works with HTML5 postMessage and resize+hash in legacy browsers https://github.com/ternarylabs/porthole
Edit: In 2014, IE6/7 usage is fairly low, and since IE8 and above all allow postMessage, I now recommend that you use that instead.
Answered by jpillora
Solution #4
To send a message back to the sender, use event.source.window.postMessage.
From Iframe
window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
if (event.data === 'GOT_YOU_IFRAME') {
console.log('Parent received successfully.')
}
}
Then the parent responds.
window.onmessage = (event) => {
event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}
Answered by Binh Ho
Solution #5
the view from the window A good property should be able to provide everything you require.
E.g.
alert(top.location.href)
See http://cross-browser.com/talk/inter-frame_comm.html
Answered by sambomartin
Post is based on https://stackoverflow.com/questions/9153445/how-to-communicate-between-iframe-and-the-parent-site