利用html5 postMessage接口跨域设置iframe大小
2017-02-25 22:44
453 查看
<!doctype html> <html> <head> <title>Document A</title> <meta charset="utf-8"> </head> <body> <iframe src="http://remote-domain.com:8080/document-B.html" id="zino_iframe"></iframe> <script type="text/javascript"> var zino_resize = function (event) { if (event.origin !== "http://remote-domain.com:8080") { return; } var zino_iframe = document.getElementById('zino_iframe'); if (zino_iframe) { zino_iframe.style.height = event.data + "px"; } }; if (window.addEventListener) { window.addEventListener("message", zino_resize, false); } else if (window.attachEvent) { window.attachEvent("onmessage", zino_resize); } </script> </body> </html>
<!doctype html> <html> <head> <title>Document B</title> <meta charset="utf-8"> <script type="text/javascript"> function iframe_resize(){ var body = document.body, html = document.documentElement, height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); if (parent.postMessage) { parent.postMessage(height, "http://my-domain.com"); } } </script> </head> <body onload="iframe_resize();"> <h4>Document B</h4> <p>Cross-Domain Iframe</p> </body> </html>
Normally, documents on different pages are able to communicate between each other only if their domains, protocols and ports match up. HTML 5 specification comes with
window.postMessage, which provides cross-domain communication between scripts.
Syntax
window.postMessage(message, targetOrigin, [transfer]);
messageMessages can be nested objects and arrays, can contain JavaScript values (strings, numbers, Dates, etc), and can contain certain data objects such as File Blob, FileList, and ArrayBuffer objects.targetOriginThe value must be either asterisk
*, slash
/or absolute URL. Otherwise a SyntaxError exception will be throw. If you know the window location, you should always provide this specific location instead of just putting an asterisk
*transfer (Optional)These objects are transferred with the message, and they are no longer usable on the sending side.
相关文章推荐
- iframe跨域通信--html5.postmessage
- 利用postmessage间接实现iframe跨域调用父页面js函数
- [HTML5_WebWorkers]利用HTML5的window.postMessage实现跨域通信
- HTML5 postMessage解决跨域、跨iframe窗口消息传递
- html5 postMessage解决iframe跨协议跨域通信问题
- html5 postMessage解决跨域、跨窗口消息传递
- 利用jsonp、iframe和location.hash解决跨域问题
- 利用P3P实现跨域设置cookie
- HTML5:使用postMessage实现Ajax跨域请求
- 使用html5 postMessage和window.name实现多浏览器跨域
- 利用iframe实现ajax跨域通信的实现原理(图解)
- 利用iframe跨域请求
- 使用HTML5中postMessage实现Ajax中的POST跨域问题
- jQuery实现跨域iframe接口方法调用
- iOS - (TableView中利用系统的 cell 设置 cell.textlabel 位置和大小)
- 用iframe设置代理解决ajax跨域请求问题
- [转]html5: postMessage解决跨域和跨页面通信的问题
- js跨域问题之跨域iframe自适应大小实现代码
- html5 postMessage解决跨域、跨窗口消息传递(转)
- HTML5之window.postMessage实现跨域传递消息