zoukankan      html  css  js  c++  java
  • Javascript使用postMessage对iframe跨域通信

    今天才发现原来有这么个好东西啊,跨域通信太方便了,
    举个小栗子:

    共两个页面,

    页面1:www.a.com/a.html
    页面2:www.b.com/b.html

    实现目标:两个网站页面实现跨域相互通信
    当前例子依赖于 jQuery 3.0

    页面代码:www.a.com/a.html

    <iframe id="myIframe" src="http://www.b.com/b.html"></iframe>
    <script>
    var $myIframe = $('#myIframe');
    // 注意:必须是在框架内容加载完成后才能触发 message 事件哦
    $myIframe.on('load', function(){
        var data = {
            act: 'article',  // 自定义的消息类型、行为,用于switch条件判断等。。
            msg: {
                subject: '跨域通信消息收到了有木有~', 
                author: 'CSDN-神神的蜗牛'
            }
        };
        // 不限制域名则填写 * 星号, 否则请填写对应域名如 http://www.b.com
        $myIframe[0].contentWindow.postMessage(data, '*');
    });
    
    // 注册消息事件监听,对来自 myIframe 框架的消息进行处理
    window.addEventListener('message', function(e){
        if (e.data.act == 'response') {
            alert(e.data.msg.answer);
        } else {
            alert('未定义的消息: '+ e.data.act);
        }
    }, false);
    </script>

    页面代码:www.b.com/b.html

    <script>
    // 注册消息事件监听,对来自 myIframe 框架的消息进行处理
    window.addEventListener('message', function(e){
        if (e.data.act == 'article') {
            alert(e.data.msg.subject);
            // 向父窗框返回响应结果
            window.parent.postMessage({ 
                act: 'response', 
                msg: {
                    answer: '我接收到啦!'
                }
            }, '*');
        } else {
            alert('未定义的消息: '+ e.data.act);
        }
    }, false);
    </script>

    Javascript使用postMessage对iframe跨域通信

    对不同浏览器应该还需要一些兼容操作,我因为只使用 Chrome 所以就偷个懒不写啦,可以去网上搜搜。

  • 相关阅读:
    一款可以下拉搜索html下拉框控件
    Springboot+JPA+Thymeleaf 校园博客完整小网站
    OAuth 2.0 认证的原理与实践
    BootStrap 专题
    Rest接口和Thymeleaf的两个坑
    Android属性动画PropertyAnimation LayoutTransition(布局容器动画)
    Android 5.0中使用JobScheduler
    遍历Map的四种方法
    Android Error:(1,N1) 错误: 需要class, interface或enum
    Android.app.SuperNotCalledException错误
  • 原文地址:https://www.cnblogs.com/zhouzme/p/5758386.html
Copyright © 2011-2022 走看看