js跨域总结(jsonp,postMessage,CORS)

来源:互联网 发布:第一版主新域名 编辑:程序博客网 时间:2024/05/18 00:18

                                                                   跨域

当协议,子域名,主域名,端口中任何一个不相同的时候,都算做不同域。不同域之间相互请求资源,就是属于跨域。Js处于安全方面考虑,不允许跨域调用其他页面的对象。

简单的说,跨域因为js同源策略的限制。a.com域名下的js无法操场b.com或c.a.com域下的对象。

现实生活中,一个公司有多个子公司,或者一个公司和另一个公司合作。这就不可避免的要出现跨域情况。

为了在必要的时候实现跨域,我们的方法有:

1、jsop跨域

JSONP和CORS的使用目的相同,但是CORS比JSONP更强大

JSONP只支持GET请求,而CORS支持所有类型的http请求。

JSONP的优势:支持老浏览器,可以向不支持cors的网站请求数据。

利用script进行跨域,script的src可以跨域请求。这样就可以把src作为请求地址。

Jsonp:json+padding(内填充)

把json当做内填充东西,填充到盒子中。

function box(json){alert(json.name)};

<script src=http://www.bb.com/jsonp.js></script>

Src中是请求的另一个页面,返回了json数据

box({name:‘lulu’})

动态生成script更好。

<script >

function oScript(oUrl){

      var  oScript=document.createElement(‘script’);

      oScript.type=’text/javascript’;

      oScript.src=oUrl;

      document.getElementsByTagName(‘head’)[0].appendChild(‘oScript’);

}

oScript(‘http://www.bb.com/jsonp.js’);

function box(json){

alert(json.name);

}

</script>

2、CORS,跨域资源共享

CORS是w3c标准,它允许浏览器向跨源服务器,发送XMLHttpRequest请求,从而克服了AjAX只能同源使用的限制。

CORS需要浏览器和服务器的同时支持。所有浏览器都支持该功能,ie10以上支持。

如何使用CORS:

只要服务端在相应时发送一个响应的标题即可。

而浏览器端还是照常使用ajax,支持get,post。

在服务端:我们对路由中的index.js中加入。在请求之前加入。

1. router.all('*'function(req, res, next) {  

2.     res.header("Access-Control-Allow-Origin""*");  

3.     res.header("Access-Control-Allow-Headers""X-Requested-With");  

4.     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  

5.     res.header("X-Powered-By",' 3.2.1')  

6.     res.header("Content-Type""application/json;charset=utf-8");  

7.     next();  

8. });  

3、h5中的postMessage

Window.postMessage API的功能是允许程序员跨域在两个窗口/frames间发送数据信息。基本上,它就像跨域的ajax,但是它不是浏览器和服务器之间的交互,它是两个客户端之间的通信。(处理ie6、ie7外,其他浏览器都支持)

postMessage方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本文档、多窗口,跨域消息传递。

postMessage(data,origin)

data:需要传递的数据,html5规范提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点,部分浏览器只能处理字符串参数,所以我们在传递从参数的时候需要使用JSON.stringify()方法对对象参数序列化。

Origin:字符串参数,指明目标窗口的源,协议+主机+端口号:url会会被忽略,所以可以不写,这个参数是为了安全考虑,postMessage()只会将message传递给指定窗口,当然如果愿意可以将参数设置为‘*’,这样可以传递给任意窗口,如果要指定和当前窗口同源的话设置为“/”;

例子:

在http://www.abc.com/index.html页面中

<div style="width:200px;float:left; margin-right:200px;border:solid 1px #333;">

       <div id="color">Frame Color</div>

 </div>

 <div>

      <iframe id="child" src="http://lsLib.com/lsLib.html"></iframe>

 </div>

在http://www.abc.com/index.html页面中向http://lsLib.com/lsLib.html传递数据,这两个页面不同域,想要通信,可以使用postMessage();

在发送信息页面这端(http://www.abc.com/index.html):

使用postMessage();

window.onload=function(){

           window.frames[0].postMessage('getcolor','http://lslib.com');

}

在另一域的页面中,我们需要对发过来的信息进行接收:

window.addEventListener('message',function(e){
                if(e.source!=window.parent) return;
                var color=container.style.backgroundColor;
                window.parent.postMessage(color,'*');
            },false);

全例子:

http://test.com/index.html

<!DOCTYPEhtml>

<html>

<head>

    <title>Post Message</title>

</head>

<body>

    <div style="width:200px;float:left; margin-right:200px;border:solid 1px #333;">

        <div id="color">FrameColor</div>

    </div>

    <div>

        <iframe id="child"src="http://lsLib.com/lsLib.html"></iframe>

    </div>

 

    <script type="text/javascript">

 

        window.onload=function(){

           window.frames[0].postMessage('getcolor','http://lslib.com');

        }

 

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

            var color=e.data;

            document.getElementById('color').style.backgroundColor=color;

        },false);

    </script>

</body>

</html>

 

http://lslib.com/lslib.html

<!doctypehtml>

<html>

    <head>

        <style type="text/css">

            html,body{

                height:100%;

                margin:0px;

            }

        </style>

    </head>

    <body style="height:100%;">

        <div id="container"onclick="changeColor();" style="widht:100%; height:100%;background-color:rgb(204, 102, 0);">

            click to change color

        </div>

        <scripttype="text/javascript">

            varcontainer=document.getElementById('container');

 

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

                if(e.source!=window.parent)return;

                var color=container.style.backgroundColor;

               window.parent.postMessage(color,'*');

            },false);

 

            function changeColor () {           

                varcolor=container.style.backgroundColor;

                if(color=='rgb(204, 102, 0)'){

                    color='rgb(204, 204, 0)';

                }else{

                    color='rgb(204,102,0)';

                }

               container.style.backgroundColor=color;

               window.parent.postMessage(color,'*');

            }

        </script>

    </body>

</html>

阅读全文
0 0
原创粉丝点击