现在的位置: 首页 > 综合 > 正文

基于HTML5的EasyXDM组件实现浏览器兼容的跨域资源请求

2014年01月04日 ⁄ 综合 ⁄ 共 3359字 ⁄ 字号 评论关闭

同源策略(http://baike.baidu.com/view/1580195.htm)指浏览器客户端的javascript脚本,只被允许访问来自同一站点的资源,阻止来自其它站点可能怀有恶意的资源。这种策略在保证安全的同时,也带来了站点间交互的诸多限制。一直以来,存在多种解决方案来实现跨域资源请求,比如基于flash或基于iFrame等等,web开发者需要选择不同的方案来兼容各种浏览器。

HTML5 XDM

近年不断发展的HTML5规范对XDM-跨文档消息传送机制进行了规范,利用postMessage()(http://www.whatwg.org/specs/web-apps/current-work/multipage/web-messaging.html#dom-window-postmessage)函数可以简单稳妥的实现对其他窗口及站点的跨文档消息传送XDM(cross-document
messaging)。

postMessage(message, targetOrigin, transfer)函数有三个参数。第一个message表示要发送的消息,第二个参数表示消息接收方所在域。第三个参数是可选的,用于渠道信息发送。

比如下面的例子简单演示了使用postMessage()向内嵌iframe发送一条消息,并指定来源自www.infoq.com,防止其中文档来源被悄悄改变。

var iframWindow = document.getElementById("theFrame").contentWindow;

  iframWindow.postMessage("private info", "http://www.infoq.com");

 

接收方www.html5.org收到XDM消息会异步触发window对象的message事件。首先验证消息来源是已知的域www.infoq.com,在处理完消息后,向发送方回复一条消息。

window.addEventListener(“message”,function(event) {

    if (event.origin == "http://www.infoq.com") { 

        processMessage(event.data);

        event.source.postMessage("Heard You", "http://www.html5.org");

    }

});

easyXDM

easyXDM (https://github.com/oyvindkinsey/easyXDM)是一款轻量级开源javascript组件,很好的实现了各种跨域解决方案的封装,来消除同源策略带来的限制,方便应用程序通过javascript
API进行跨域通讯。easyXDM借助传输栈允许两个窗口双向交换基于字符串的消息,支持双向通讯、可靠性、队列和发送方验证等。对于支持HTML5的浏览器如IE 8+, Opera 9+,Firefox 3+, Safari 4+, Chrome 2+等直接采用HTML5的postMessage(),对于其他非HTML5浏览器,则根据当前浏览器优先选择最有效的方法实现跨文档消息传送,比如加载swf文件组件,创建iFrame等。

 

easyXDM包含两个基本对象。

easyXDM.Socket对象包装了传输栈,允许在通讯的消费者(客户端)和提供者(服务端)之间通讯,并定义一系列属性用于异步事件。

服务端首先建立Socket:

var socket = new easyXDM.Socket({

        onMessage:function(message, origin) {

            //do something with message

        }

    });

客户端创建Socket并进行连接:

    var socket = new easyXDM.Socket({

        remote: "http://path.to/provider/"//
the path to the provider

        onMessage:function(message, origin) {

            //do something with message

        }

    });

    socket.postMessage("hello world");

 

easyXDM.Rpc对象允许创建带有代理对象进行远程方法调用。Rpc与Socket使用相同的传输栈和配置属性。

在服务端配置被调用的远程对象:

var rpc = new easyXDM.Rpc({},

    {

        local: {

            helloWorld: function(one, two, three, successFn, errorFn){

                // here we expose a simple method with three arguments

                // that returns an object

                return {

                    this_is: "an object"

                };

            }

        },

        remote: {

            helloWorld:{

                // here we tell the Rpc object to stub a method helloWorld for us

            }

        }

    });

在客户端可以进行基于JSON的远程方法调用:

rpc.helloWorld(1,2,3function(response){

        // here we can do something with the return value from `helloWorld`

    }, function(errorObj){

        // here we can react to a possible error

    };

 

跨域资源请求

在web开发中跨域资源请求相当常用。借助XDM,可以将资源内容作为消息内容来传送。

下面举例如何使用easyXDM来跨站点文件请求:站点client.com/index.html获取remote.com/list.xml 这种典型场景。首先在remote.com放置代理,注意这个代理是纯HTML文件,例如remote.com/agent.html

 

在客户端client.com/index.html引用easyxdm.js后,添加以下代码,发起远程连接并准备好回调函数来处理XML文件内容。

 

var socket = new easyXDM.Socket({

    remote: "http://remote.com/agent.html",

    onMessage:function(message, origin) {

     var data = $.parseXML(message);

        //do something with message data

    }

});

 

在被请求的远程服务端remote.com/agent.html,添加以下代码:list.xml的内容将被缓存并发送

$.ajax({

    type: "GET",

    url: “list.xml",

    dataType: "text",

    success: function (data) {

        var socket = new easyXDM.Socket(

            {

                onReady: function(message, origin){ }

            }

        );

    socket.postMessage('' + data);

    }

});

 

 

小结:easyXDM开源组件封装和支持HTML5的postMessage()和其他传统跨文档消息传送XDM方案,允许web开发人员可以方便安全的实现跨域资源请求,并方便的兼容不同的浏览器。

抱歉!评论已关闭.