iframe 中的网站不在同一个域中,但两者都是我的,我想iframe
在父站点和父站点之间进行通信。是否可以?
iframe 和父站点之间如何通信?
IT技术
javascript
html
ajax
iframe
2021-02-08 01:27:14
6个回答
对于不同的域,无法直接调用方法或访问 iframe 的内容文档。
您必须使用跨文档消息传递。
父级 -> 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', '*')
在 2018 年和现代浏览器中,您可以将自定义事件从 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 和带有调整大小+哈希的旧浏览器https://github.com/ternaryabs/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.')
}
}
然后从父母说回来。
window.onmessage = (event) => {
event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}
该window.top
物业应该能够满足您的需求。
例如
alert(top.location.href)
其它你可能感兴趣的问题