【9大跨域解决方案】window.name解决跨域的原理

window.name跨域

首先,当我们尝试去查看一个普通页面下,window的属性时候,确实存在name属性,并且值为空。那么,这个window.name存在的意义是什么呢?就如同标题所讲,可以解决跨域问题。那么,我们下面详细讲解下如何利用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);//yuhua
                  }
             }
         </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 = 'yuhua';
            </script>
        </body>
        </html>
    
  • 现象:通过c.html设置window.name=‘yuhua’,然后a.html会打印’yuhua’
  • 原因分析:

    window.name有如下特征:
    1. 每个窗口都有自己独立的window.name
    2. 当一个页面载入多个页面的时候,共享同一个window.name,该页面以及所有载入的页面都可以对共享的window.name进行读写。
    3. window.name一直会存在当前窗口中,即时有新页面载入,window.name也不会变化(所以本例中,c页面给window.name一个值,即便c页面销毁,a页面依旧能够得到window.name,且该值就是c页面给的这个值)
    4. window.name可以存储不超过2M的数据,传递的数据都会变成string类型。
    以上原因分析4点均为重点


实现跨域的9种方法(点击可跳转详情页面)

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值