美文网首页程序员
postMessage解决跨域、跨窗口消息传递

postMessage解决跨域、跨窗口消息传递

作者: IT小C | 来源:发表于2016-03-24 08:50 被阅读361次

平时做web开发的时候关于消息传递,除了客户端与服务器传值还有几个经常会遇到的问题
1.页面和其打开的新窗口的数据传递
2.多窗口之间消息传递
3.页面与嵌套的iframe消息传递
4.上面三个问题的跨域数据传递
这些问题都有一些解决办法,但html5引入的message的API可以更方便、有效、安全的解决这些难题。postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

postMessage(data,origin)方法接受两个参数

1.data:要传递的数据,html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化,在低版本IE中引用json2.js可以实现类似效果。

2.origin:字符串参数,指明目标窗口的源,协议+主机+端口号[+URL],URL会被忽略,所以可以不写,这个参数是为了安全考虑,postMessage()方法只会将message传递给指定窗口,当然如果愿意也可以建参数设置为"*",这样可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。

父页面

<!DOCTYPE html>
<html>
<head>
    <title>Post Message</title>
</head>
<body>
    <div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
        <div id="color">Frame Color</div>
    </div>
    <div>
        <iframe id="child" src="http://lsLib.com/lsLib.html"></iframe>
    </div>

    <script type="text/javascript">

        window.onload=function(){
            window.frames[0].postMessage('getcolor','http://lslib.com');
        }

        window.addEventListener('message',function(e){
            var color=e.data;
            document.getElementById('color').style.backgroundColor=color;
        },false);
    </script>
</body>
</html>

iframe页面

<!doctype html>
<html>
    <head>
        <style type="text/css">
            html,body{
                height:100%;
                margin:0px;
            }
        </style>
    </head>
    <body style="height:100%;">
        <div id="container" onclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
            click to change color
        </div>
        <script type="text/javascript">
            var container=document.getElementById('container');

            window.addEventListener('message',function(e){
                if(e.source!=window.parent) return;
                var color=container.style.backgroundColor;
                window.parent.postMessage(color,'*');
            },false);

            function changeColor () {            
                var color=container.style.backgroundColor;
                if(color=='rgb(204, 102, 0)'){
                    color='rgb(204, 204, 0)';
                }else{
                    color='rgb(204,102,0)';
                }
                container.style.backgroundColor=color;
                window.parent.postMessage(color,'*');
            }
        </script>
    </body>
</html>

相关文章

网友评论

    本文标题:postMessage解决跨域、跨窗口消息传递

    本文链接:https://www.haomeiwen.com/subject/pakrlttx.html