美文网首页
跨域的几种实现方式

跨域的几种实现方式

作者: Gia_Mo | 来源:发表于2017-07-07 00:08 被阅读0次
JSONP
// 前端代码
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .ct {
      width: 300px;
      margin: 0 auto;
      margin-top: 20px;
      border: 1px solid #ccc;
    }
    .ct img {
      width: 300px;
      height: 200px;
    }
    .ct h3 {
      font-size: 14px;
      padding: 5px;
    }
    .ct p {
      font-size: 12px;
      padding: 5px;
    }
    .btn {
      display: block;
      width: 80px;
      height: 40px;
      font-size: 12px;
      margin: 0 auto;
      margin-top: 10px;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="ct">
     ![](http://a.jpg)
      <h3 class="title">宠物的斑斑劣迹:偷吃毫无悔意</h3>
      <p class="content">我们都以为自己出门时、宠物们都会乖乖待在家里,但一些照片显示,你想得太美了。</p>
    </div>
    <button class="btn">换个新闻看看</button>
  </div>

  <script>

    var btn = document.getElementsByClassName('btn')[0];
    var ct = document.getElementsByClassName('ct')[0];
    btn.addEventListener('click', function(){
      var script = document.createElement("script");
      script.src = "http://localhost:8080/getNews?callBack=switchNews";
      document.head.appendChild(script);
      document.head.removeChild(script);
    })

    function switchNews(data){
      var html = '';
      html += '![](' + data.img + ')';
      html += '<h3 class="title">' + data.title + '</h3>';
      html += '<p class="content">' + data.content + '</p>';
      ct.innerHTML = html;
    }

  </script>
  
</body>
</html>

// 后端代码
app.get('/getNews',function(req, res){
  var news = [
    {
      img:"http://n.sinaimg.cn/tech/transform/20170701/QJiR-fyhskrp9685559.jpg",
      title: "极地生物散发神秘魅力",
      content: "这些极具视觉冲击效果画面向我们揭示了生活在格陵兰岛冰盖下的神秘生物。"
    },
    {
      img:"http://n.sinaimg.cn/tech/transform/20170701/cycK-fyhskrp9682498.jpg",
      title: "南非蜥蜴觅食遭蝴蝶调戏",
      content: "一头荧光黄色的蜥蜴正在寻找自己的下一餐,遇到了一群蝴蝶。"
    },
    {
      img:"http://n.sinaimg.cn/tech/transform/20170630/4f0z-fyhskrp8448536.jpg",
      title: "澳袋鼠代班当牧羊犬",
      content: "当Lochie Ireson看到一头“牧羊犬袋鼠”跳上一头羊的背,把羊群赶进围栏的画面时,他简直惊呆了。lalalalalalalaallalal"
    }
  ];

  var cb = req.query.callBack;
  var index = parseInt(Math.random()*news.length);
  if (cb) {
    res.send(cb + '(' + JSON.stringify(news[index]) + ')');
  }
})
CORS
// 前端代码
  <script>

    var btn = document.getElementsByClassName('btn')[0];
    var ct = document.getElementsByClassName('ct')[0];
    btn.addEventListener('click', function(){
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)){
          var data = JSON.parse(xhr.responseText);
          switchNews(data);
        } 
      }
      xhr.open('get', 'http://b.supoxiao.com:8080/getNews', true);
      xhr.send();
    })

    function switchNews(data){
      var html = '';
      html += '![](' + data.img + ')';
      html += '<h3 class="title">' + data.title + '</h3>';
      html += '<p class="content">' + data.content + '</p>';
      ct.innerHTML = html;
    }

  </script>

// 后端代码
app.get('/getNews', function(req, res){
  var news = [
    {
      img:"http://n.sinaimg.cn/tech/transform/20170701/QJiR-fyhskrp9685559.jpg",
      title: "极地生物散发神秘魅力",
      content: "这些极具视觉冲击效果画面向我们揭示了生活在格陵兰岛冰盖下的神秘生物。"
    },
    {
      img:"http://n.sinaimg.cn/tech/transform/20170701/cycK-fyhskrp9682498.jpg",
      title: "南非蜥蜴觅食遭蝴蝶调戏",
      content: "一头荧光黄色的蜥蜴正在寻找自己的下一餐,遇到了一群蝴蝶。"
    },
    {
      img:"http://n.sinaimg.cn/tech/transform/20170630/4f0z-fyhskrp8448536.jpg",
      title: "澳袋鼠代班当牧羊犬",
      content: "当Lochie Ireson看到一头“牧羊犬袋鼠”跳上一头羊的背,把羊群赶进围栏的画面时,他简直惊呆了。lalalalalalalaallalal"
    }
  ];

  var index = parseInt(Math.random()*news.length);

  res.header("Access-Control-Allow-Origin", "http://a.supoxiao.com:8080");
  res.send(news[index]);


});
降域

对于页面中使用iframe嵌套另外的网站时,如果符合同源策略,就可以通过window.frames[index].document操作对应iframe里的网站,如果不符合,则不能相互访问,但是如果这些网站有着相同的主网站,则可以通过降域实现跨域。例如:a.test.com:8080和b.test.com:8080的主域名为test.com:8080

原理

在script标签里写上document.domain = "主域名",就可以实现降域,
然后就可以使用window.frames[index].document操作对应iframe里的网站,实现跨域。

// 创建a.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    iframe {
      width: 500px;
      height: 200px;
    }
    .wrapper {
      margin-left: 100px;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="ct">
      <h1>降域</h1>
      <input type="text" placeholder="hello">
    </div>
    
    <iframe src="http://b.supoxiao.com:8080/b.html"></iframe>
  </div>
  
  <script>
    document.querySelector("input").addEventListener("input",function(){
      window.frames[0].document.querySelector("input").value = this.value;
    })
    document.domain = "supoxiao.com";

  </script>
  
</body>
</html>

// 创建b.html

<html>
<head>
  <meta charset="utf-8">
  <style>
  </style>
</head>
<body>

    <p>我是b</p>

    <input type="text" placeholder="hello2">

  
  <script>

    document.domain = "supoxiao.com";
  </script>
  
</body>
</html>
postMessage

postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。postMessage(data,origin)方法接受两个参数,data是要传递的数据,origin可以设置目标窗口的url,只包括协议、域名、端口。也可以设置为"*",表示传递给任意窗口

原理

postMessage可向任意窗口发送数据,由目标窗口选择接受数据。
通过postMessage()发送数据,然后再写一个监听函数就可以实现跨域操作。

// 创建a.html
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    iframe {
      width: 500px;
      height: 200px;
    }
    .wrapper {
      margin-left: 100px;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="ct">
      <h1>postMessage</h1>
      <input type="text" placeholder="hello">
    </div>
    
    <iframe src="http://b.supoxiao.com:8080/b.html"></iframe>
  </div>
  <script>
    document.querySelector("input").addEventListener("input",function(){
      window.frames[0].postMessage(this.value,"*");
    })
    
    window.addEventListener("message",function(e){
      document.querySelector("input").value = e.data;
    })
  </script>
  
</body>
</html>

// 创建b.html
<html>
<head>
  <meta charset="utf-8">
  <style>
  </style>
</head>
<body>

    <p>我是b</p>

    <input type="text" placeholder="hello2">

  
  <script>
  var input = document.querySelector("input");
  window.addEventListener("message",function(e){
    input.value = e.data;
  })
  input.addEventListener("input",function(){
    window.parent.postMessage(this.value,"*")
  })
  </script>
  
</body>
</html>

相关文章

  • #hello,JS:15 同源策略 & 跨域(JSONP)

    跨域有几种常见的方式?你有没有跨域使用的经验? 方式: 使用jsonp实现跨域?使用cors实现跨域?浏览器另类的...

  • Ajax 请求和跨域

    跨域的几种方式: cors方式 cross-orign-resource-shareing(跨域)参考:http:...

  • 跨域的几种实现方式

    JSONP JSONP 是JSON with padding(填充式JSON 或参数式JSON)的简写;JSONP...

  • 跨域的几种实现方式

    概念1:同源策略 同源策略,Same-origin policy,浏览器处于安全考虑,只允许与本域下的接口交互。不...

  • 跨域的几种实现方式

    JSONP CORS 降域 对于页面中使用iframe嵌套另外的网站时,如果符合同源策略,就可以通过window....

  • 跨域的几种实现方式

    一、背景 同源策略 同源策略可以理解为浏览器的一种安全机制,浏览器只允许与本域下的接口进行交互。不同源的客户端在没...

  • 跨域的几种实现方式与原理

    在实际工作中,遇到前后端进行数据交互,经常会碰到请求跨域,今天就来探讨一下什么是跨域以及跨域的几种实现方式! 什么...

  • 跨域的几种演示

    几种跨域方式的代码演示 JSONP 优点: 它不像XMLHttpRequest 对象实现 Ajax 请求那样受到同...

  • 跨域问题

    通过XHR实现Ajax通信的一个主要限制,来源于跨域安全策略。解决跨域总结了几下几种方式:一、跨源资源共享(COR...

  • springboot 三种跨域处理方式

    springboot 三种跨域处理方式:1.通过Filter方式实现全局跨域2.通过Interceptor方式实现...

网友评论

      本文标题:跨域的几种实现方式

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