跨域解决方案之三---postMessage

…….续前缘

前文说到的jsonp, 正在向前端靠拢. 而本文所说的postMessage, 跟后台已经没有任何关系了. 因为用的是HTML5 新API: canvas, video, audio, history, postMessage.
百度百科对它的解释如下: PostMessage是Windows API(应用程序接口) 中的一个常用函数,用于将一条消息放入到消息队列中。
战前准备: 两个**非同源**website, 请见jsonp的战前准备
请求方(request)和响应方(response). request.html如下(wamp):

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>请求方</title>
        <meta content="initial-scale=1.0,maximum-scale=1.0,width=device-width" name="viewport">
    </head>
    <body>
        <div class="form-wrap">
            <button ontouchstart="fnSearch();">查询</button>
        </div>
    </body>
    <script>
        function fnSearch(){
    var newWindow = window.open('http://localhost:8020/test2/response.html');
    window.addEventListener('message', function(e){
        if (e.data) {
            newWindow.postMessage('hello world!', e.origin);
            console.log(e);
        }
    });
}
    </script>
</html>

response.html如下(HBuilder):

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>手机时间选择</title>
        <meta content="initial-scale=1.0,maximum-scale=1.0,width=device-width" name="viewport">
    </head>
    <body>
        <div class="form-wrap">
            <button id="search" type="button">查询</button>
        </div>
    </body>
    <script type="text/javascript">
        document.getElementById('search').onclick = function(){
            window.opener.postMessage('测试123', 'http://localhost:80/chart/index.html');
            window.addEventListener('message',function(e){
                console.log(e);
            }, false);
        };
    </script>
</html>

在两个页面的控制台就可以看到交互的信息了, 如果有任何问题, 可以给我留言啊. 我会及时回复滴……………………

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章