zoukankan      html  css  js  c++  java
  • postMessage解决跨域问题

    postMessage解决跨域问题

    html5有了很多新的功能,解决了以前很多一些很纠结的问题,比如说跨域访问数据,html5中就有了postMessage来解决了这一问题,它提供的api也一样简单易用。

    我们可以在主页面中发送消息给不同域的iframe信息,也可以在不同域的iframe之间传输数据。利用postMessage来发送数据,用onMessage来监听数据。就像webWorker一样,它的api跟postMessage很相似。

    处理主页面跟iframe之间的数据传输,我们的代码应该像下面这样:

    主页面代码为如下:

    window.frames[0].postMessage(msg, '*');

    iframe中的代码监听发送来的消息如下:

    function onmessage(e) {

      //todo...

    }

    if (typeof window.addEventListener != 'undefined') {

      window.addEventListener('message', onmessage, false);

    } else if (typeof window.attachEvent != 'undefined') {

      window.attachEvent('onmessage', onmessage);

    }

    当然两边也可以互传消息和互相监听事件。添加对应的代码即可。

    如果是处理主页面中包含的两个不同域iframe,方式也十分简单,只要能够获取的到页面的对应iframe对象即可。通过window.parent.frames['iframe id']或者window.parent.frames[index]取得对应的iframe,然后对该iframe绑定postMessage.

    window.parent.frames[0].postMessage(msg, '*');

    window.addEventListener('message', function(e){

      console.log(e.data);

    });

    在上面的postMessage中接收两个参数,一个是传递的信息,另一个是域名限制,如果允许任何域名访问的话,那就使用*号,如果希望限制在某个域中的话,就将*号改为对应的域名,比如:

    window.parent.frames[0].postMessage(msg, 'http://www.xx.com');

    对应的在onmessage回调函数中,我们可以通过e.origin来获得他的限制域名,并通过判断来决定如何访问,或不能访问。

    function onmessage(e){

      if (e.origin !== 'http://www.xx.com') return;

      //....

    }

    文章原始出处:http://www.36ria.com/3890

  • 相关阅读:
    Navicat Premium 12.1.12.0破解版激活
    vConsole调试器
    使用DbFunctions来解决asp.net mvc ef按照日期分组数据
    谷歌浏览器如何安装CRX插件?crx离线插件安装方法
    ASP.NET MVC——CodeFirst开发模式
    Sql server 事务的两种用法
    SQL Server 存储过程
    JqueryMobile新手问题大全
    .net core 轻量级容器 ServiceProvider 源码分析
    Centos7 使用Docker 部署mssql 2017
  • 原文地址:https://www.cnblogs.com/moyiqing/p/postmessage.html
Copyright © 2011-2022 走看看