Dan*_*Fox 167 html javascript ajax iframe
iframe中的网站不在同一个域中,但两者都是我的,我想iframe在父网站之间进行通信.可能吗?
use*_*621 279
对于不同的域,无法直接调用方法或访问iframe的内容文档.
您必须使用跨文档消息传递.
例如在顶部窗口中:
myIframe.contentWindow.postMessage('hello', '*');
Run Code Online (Sandbox Code Playgroud)
在iframe中:
window.onmessage = function(e){
if (e.data == 'hello') {
alert('It works!');
}
};
Run Code Online (Sandbox Code Playgroud)
如果要将iframe中的消息发布到父窗口
window.top.postMessage('hello', '*')
Run Code Online (Sandbox Code Playgroud)
Str*_*e Q 28
它必须在这里,因为2012年接受了答案
在2018年和现代浏览器中,您可以将自定义事件从iframe发送到父窗口.
IFRAME:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
Run Code Online (Sandbox Code Playgroud)
父:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
Run Code Online (Sandbox Code Playgroud)
PS:当然,您可以以相反的方向发送相反方向的事件.
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
Run Code Online (Sandbox Code Playgroud)
jpi*_*ora 14
这个库支持HTML5 postMessage和旧版浏览器resize + hash https://github.com/ternarylabs/porthole
编辑:现在在2014年,IE6/7的使用率相当低,IE8及以上版本都支持,postMessage所以我现在建议只使用它.
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
使用event.source.window.postMessage发回给发件人。
来自 iframe
window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
if (event.data === 'GOT_YOU_IFRAME') {
console.log('Parent received successfully.')
}
}
Run Code Online (Sandbox Code Playgroud)
然后从父母说回来。
window.onmessage = (event) => {
event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
122736 次 |
| 最近记录: |