利用html5 postMessage接口跨域设置iframe大小

<!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 οnlοad="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]);

message
Messages 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.
targetOrigin
The 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.

转载于:https://www.cnblogs.com/kzwrcom/p/6443172.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值