window.postMessage
在 HTML5 中新增了 postMessage 方法,postMessage 可以实现跨文档消息传输(Cross Document Messaging)
postMessage(data,origin)
- data:要传的数据
- origin: 字符串参数,指明目标窗口的源,协议+主机+端口号。
如果为*则是所有的窗口,如果要指定和当前窗口同源的话设置为"/"。
iframe 向 父窗口通信:
子窗口向父窗口发送消息,其实是在子窗口里拿到父窗口的句柄,然后用父窗口的postMessage去发送内容。
//iframe
const parent = window.parent;
parent.postMessage(data, '*')
//父页面
window.addEventListener(
'message',
function(e) {
console.log(e);
console.log(e.data);
},
false
)
父窗口 向 iframe 通信
//父页面
window.frames[0].postMessage(data, 'http://test.com:port') //第二个参数为子页面地址
//iframe
window.addEventListener(
'message',
function(e) {
if (e.source != window.parent) return
console.log(e.data)
// message的回调里有三个非常重要的属性:data、origin、source
// e.data:从其他窗口带过来的数据
// e.origin:调用 postMessage 时消息发送方窗口的 origin . 这个字符串由 协议、“://“、域名、“ : 端口号”拼接而成。
// e.source:对发送消息的窗口对象的引用; 您可以使用此来在具有不同 origin 的两个窗口之间建立双向通信。
// 例如:event.source.postMessage("hi there yourself! the secret response " + "is: rheeeeet!", event.origin);
},
false
)
1、contentWindow
document.getElementById(“myiframe”).contentWindow,
得到iframe对象后,就可以通过contentWindow得到iframe包含页面的window对象了