美文网首页
JS四种跨域方式

JS四种跨域方式

作者: lmmy123 | 来源:发表于2018-01-12 11:12 被阅读23次

    1.JSONP

    script标签是不受同源策略限制的,它可以载入任意地方的javascript文件,而不要求同源

    jsonp的理念是:我和服务器端约定好一个函数名,当我请求文件的时候,服务端返回一段JavaScript,这段JavaScript调用这个约定好的函数,并且将数据当做参数传入

    demo:

    index.html

    <script>

      function  getWeather(data){

                  console.log(data)

          }

    </script>

    <script src="http://x.y.com/xx.js">

    http://x.y.com/xx.js

    getWeather({

                "城市": “北京”,

                 "天气":大雾“”

    })


    2.document.domain

    使用条件:

     1.有其他页面window 对象的引用

      2.二级域名相同

      3.协议相同,

       4.端口相同

    document.domain默认的值是整个域名,所有即使两个域名的二级域名一样,那么他们的document.domain也不一样

    demo

    两个网站: http://wenku.baidu.com   http://zhidao.baidu.com

    这两个网站都是 http协议, 端口都是80, 二级域名都是 baidu.com

    打开http://wenku.baidu.com/,在 console 中输入代码:

    document.domain ='baidu.com';

    varotherWindow =window.open('http://zhidao.baidu.com/');

    我们现在已经发现百度知道的网页已经打开了,在百度知道网页的 console 中输入以下代码:

    document.domain ='baidu.com';

    现在回到百度文库的网页,我们就可以使用百度知道网页的window对象来操作百度知道的网页了。例如:

    vardivs = otherWindow.document.getElementsByTagName('div');

    这种方法主要用在控制<iframe>的情况中

    我们在 iframe.html 中使用 JavaScript 将document.domain设置好,也就是 example.com。

    在 index.html 执行以下脚本:

    variframe =document.getElementById('iframe');document.domain ='example.com';iframe.contentDocument;// 框架的 document 对象

    iframe.contentWindow;// 框架的 window 对象

    这样,我们就可以获得对框架的完全控制权了。


    3.window.name

    随意打开一个页面,输入以下代码:

    window.name ="My window's name";location.href ="http://www.qq.com/";

    再检测window.name:

    window.name;// My window's name

    可以看到,如果在一个标签里面跳转网页的话,我们的window.name是不会改变的。

    基于这个思想,我们可以在某个页面设置好window.name的值,然后跳转到另外一个页面。在这个页面中就可以获取到我们刚刚设置的window.name了。

    由于安全原因,浏览器始终会保持window.name是string类型。

    这种方法与document.domain方法相比,放宽了域名后缀要相同的限制,可以从任意页面获取string类型的数据。


    4.html5 postMessage

    windowObj.postMessage(message, targetOrigin)

    windowObj: 接受消息的window对象

    message:在最新的浏览器中可以是对象

    targetOrigin: 目标的源,*表示任意

    message 事件就是用来接收 postMessage发送过来的请求的,函数参数的属性有下几个:

       :origin:发送消息的window的源

        :data: 数据

         :source: 发送消息的window对象

    demo:

    var windowObj= window;//可以是其他的  window对象的引用

    var  data  =null;

    addEventListener("message", function(e){

    if(e.origin == 'http://jasonkid.github.ib/fezone'){

             data= e.data;

            e.source.postMessage('got  it', '*')

        }

    })

    文章来源: https://segmentfault.com/a/1190000003642057

    相关文章

      网友评论

          本文标题:JS四种跨域方式

          本文链接:https://www.haomeiwen.com/subject/owwxoxtx.html