4.iframe跨域传值

449 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

概述:因为一些项目的要求,所以需要进行iframe跨域传值

上干货

 postMessage跨域  

 postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数不多可以跨域操作的window属性之一,它可用于解决以下方面的问题:   a.) 页面和其打开的新窗口的数据传递   b.) 多窗口之间消息传递   c.) 页面与嵌套的iframe消息传递   d.) 上面三个场景的跨域数据传递  

用法:

 postMessage(data,origin)方法接受两个参数   

a.)data: html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。   b.)origin: 协议+主机+端口号,也可以设置为"*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。  

a.html:(www.domain1.com/a.html)

<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
        var data = {
            name: 'aym'
        };
        // 向domain2传送跨域数据
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
    };

    // 接受domain2返回数据
    window.addEventListener('message', function(e) {
        alert('data from domain2 ---> ' + e.data);
    }, false);
</script>

b.html:(www.domain2.com/b.html

<script>
    // 接收domain1的数据
    window.addEventListener('message', function(e) {
        alert('data from domain1 ---> ' + e.data);
        try{
         var data = JSON.parse(e.data);
         if (data) {
            data.number = 16;
            // 处理后再发回domain1
            window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
          }
        }catch(e){}
    }, false);
</script>

补充知识:

window.name跨域

  • 前提准备:
  1. a.html,起在localhost:3000上
  2. b.html,起在localhost:3000上
  3. c.html,起在localhost:4000上 可见a和b是同域的,c是独立的

需求:在a页面获取c页面发送的数据。

思路:a先引用c,c把值放到window.name中,然后把a引用的地址改到b

    //a.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>a.html</title>
    </head>
    <body>
        <iframe id="iframe" src="http://localhost:4000/c.html" frameborder="0" "load()"></iframe>
        <script type="text/javascript">
            let first = true;//第一次加载
            function load(){
              if(first){
                  let iframe = document.querySelector("#iframe");
                  iframe.src = 'http://localhost:3000/b.html';
                  first = false;
              }else{
                  console.log(iframe.contentWindow.name);//xsw
              }
         }
     </script>
    </body>
    </html>

    //b.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
     <title>Document</title>
    </head>
    <body>

    </body>
    </html>

    //c.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        c页面
        <script type="text/javascript">
            window.name = 'xsw';
        </script>
    </body>
    </html>

  • 现象:通过c.html设置window.name=‘xsw’,然后a.html会打印’xsw’