简述用postMessage解决iframe自适应高度问题;
postMassage:
postMessage可以使不同域下的页面实现相互通信
sending message
window.postMessage(message,targetOrigin),window为信息接收方的所在的window对象,比如要想A页面向B页面发送信息,则应在A页面执行window_B.postMessage(),以下几种方式获取window:
- var targetWindow = window.open();
- var targetWindow = frames[n].contentWindow;
- 如果是iframe向父页面传信息则是window.top
message为传递的信息,可以为几乎任意类型的值,因为该参数在传递时被自动序列化,且为比json更彻底的序列化,所以各种类型值都可以。
targetOrigin为信息接收方的url,接收方的 protocol,port,hostname必须同时与targetOrigin保持一致才可以接收到该信息。*可以匹配任意url但是出去安全考虑不推荐使用。
listener
消息接收方要想得到消息需要监听message事件,监听到的messageEvent对象常用属性为data,origin,source
adaptive
回到开始的问题,则只要在onload中获取到当前文档的高度,然后作为message传递给父页面就可以了,不在onload中获取到的高度不一定准确。
籽料: