iframe中的网站不在同一个域中,但都是我的,我想在iframe和父站点之间进行通信。这可能吗?
当前回答
在2018年和现代浏览器中,您可以将自定义事件从iframe发送到父窗口。
iframe:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
家长:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
PS:当然,你也可以以相反的方向发送事件。
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
其他回答
使用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.')
}
}
然后从父母那里说回来。
window.onmessage = (event) => {
event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}
你也可以使用
postMessage消息(,' * ');
在2018年和现代浏览器中,您可以将自定义事件从iframe发送到父窗口。
iframe:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
家长:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
PS:当然,你也可以以相反的方向发送事件。
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
这个库支持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
对于不同的域,不可能直接调用方法或访问iframe的内容文档。
您必须使用跨文档消息传递。
Parent -> iframe
例如在顶部窗口:
myIframe.contentWindow.postMessage('hello', '*');
在iframe中:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
Iframe ->父级
例如在顶部窗口:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
在iframe中:
window.top.postMessage('hello', '*')
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求