跨文档消息传递postMessage方法使用

<body>
//主页代码
<h3>这里是主页米娜</h3>
<iframe src="boxShadow.html" frameborder="0"></iframe>
<h4>点我发送消息</h4>

<script type="text/javascript">
    $(function(){
       //接收回执消息
        $(window).on('message',function(e){
            var getDa= e.originalEvent;
            console.log('mainPage'+getDa);
        });
        //发送消息到目标页面
        $('h4').on('click',function(){
            var iContent=$('iframe')[0].contentWindow;
            iContent.postMessage('I have send','http://localhost:63342');
        });

    })
</script>
</body>

//嵌入的iframe页面代码
<script type="text/javascript">
    $(function(){
        //接收消息
        $(window).on('message',function(e){
            var orOBj= e.originalEvent;
            console.log('boxShadow'+orOBj);
            //验证来源并且发送回执消息
            if(orOBj.origin=='http://localhost:63342'){
                var orWind=orOBj.source;
                orWind.postMessage('呵呵,我收到了','http://localhost:63342')
            }
        });
    })
</script>
                    

猜你喜欢

转载自www.cnblogs.com/chjb/p/9287747.html