zoukankan      html  css  js  c++  java
  • window.name跨域

    window.name?

    每一个页面都有一个自己的window,而window.name是window的名字。

    window.name跨域原理

    window对象有个name属性,该属性有个特征:即在一个窗口(window)的生命周期内,窗口载入的所有的页面都是共享一个 window.name的,每个页面对window.name都有读写的权限,window.name是持久存在一个窗口载入过的所有页面中的,并不会因 新页面的载入而进行重置。
    即我们在"http://www.baidu.com"页面的控制台设置window.name = "name=123",然后我们在控制台修改window.location.href = "http://www.youku.com",跳转页面后我们在控制台打印window.name,我们发现结果为我们刚才设置的'name=123'
    利用此原理我们可以利用window.name来传递信息,且window.name可传递的信息量为2M,足够使用了。

    操作如下

    比如我们想要在a.html页面获取data.html页面传递的信息

    首先我们在htttp://www.example.com/data.com页面下添加如下代码:

     <script>
        // 将我们想传递的信息赋值到data.html页面的window.name上
            window.name = "{"name":"lyl", "age": 18}";
        </script>

    然后我们如何修改data.html页面的window.href,将其改变我a.html呢?显然我们无法在data.html页面修改window.href,所以我们利用一个隐藏iframe将data.html页面嵌入到a.html页面中,让iframe作为一个代理人,让iframe去代替我们获取数据
    虽然iframe能获取到data.html页面的数据,那a.html页面如何向iframe获取数据呢,直接获取?
    但是a.html和iframe不同域,受同源策略的影响,我们无法直接获取,怎么办?
    这时,聪明的你灵机一动,想着既然改变iframe页面location,该页面的window.name值不变,而且iframe.contentWindow代表iframe页面的window,此时的你默默的将iframe.contentWindow.href改为和a.html页面同源的,拿走数据后,带着莫名的笑意看我我们一群迷茫的愤青(O(∩_∩)O哈!)

    a.html页面代码如下:

    <script>
            function getData(url) {
                var iframe = document.createElement('iframe');
                iframe.style.display = "none";
                var state = 0;
                iframe.onload = function () {
                    if(state === 1) {
                        var data = iframe.contentWindow.name;
                        console.log(data);
                        // 获取到数据后将隐藏的iframe去除
                        iframe.contentWindow.document.write('');
                        iframe.contentWindow.close();
                        document.removeChild(iframe);
                    }else if(state === 0) {
                        state = 1;
                        iframe.contentWindow.location.href = window.location.href;
                    }
                }
    
                iframe.src = url;
                document.body.appendChild(iframe);
            }
        </script>
     

    参考

    1. http://www.cnblogs.com/zichi/p/4620656.html

    2. http://www.cnblogs.com/fliu/articles/5249130.html

  • 相关阅读:
    集合中的3个经典练习题
    创建泛类集合List以及数组转集合,集合转数组的应用
    添加一个txt文件(例如在桌面),利用后台对文件写入内容
    File类的创建,删除文件
    集合中存放随机数的问题之解析
    集合中的类型转化 以及求集合中元素的最大值,平均值
    response.sendRedirect()使用注意事项
    request.getContextPath是为了解决相对路径的问题,可返回站点的根路径
    java中instanceof的用法
    getParameter 与 getAttribute的区别
  • 原文地址:https://www.cnblogs.com/Walker-lyl/p/7454522.html
Copyright © 2011-2022 走看看