跨域-Hash

2017-01-04  本文已影响57人  duJing
问题描述:
使用location.hash + iframe实现跨越
现在本地页面a.html要访问异域b.html的数据
怎么办?
环境配置:
a.html 和 c.html我们放在php的wamp中运行
他们的地址为:http://localhost/a.html和http://localhost/c.html
b.html 的代码,我放在lamport.me/b.html中

原理:
1.a.html中有一个隐藏的frame,该frame指向异域lamport.me的b.html,且传递hash值给b.html
2.b.html获取hash值,生成data值,然后动态创建iframe,该iframe将data值传给与a.html同域的c.html
3.因为c.html与a.html同域,可以传值。
如果该文件不能访问,你可以在自己的wamp中配置一个虚拟主机进行访问
虚拟主机的配置地址:
http://blog.csdn.net/super_yang_android/article/details/53991982
本地http://localhost/a.html
<!doctype html>
<html>
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    <title>localhost:a.html</title>

    <style type="text/css">

    </style>
</head>

<body>
<script type="text/javascript">
    alert('我是a页面');
    function sendRequest(){
        //动态创建个iframe
        var ifr = document.createElement('iframe');
        ifr.style.display = 'none';
        //跨域发送请求给b.html,参数是#sayHello
        ifr.src = 'http://lamport.me/b.html#sayHello';
        document.body.appendChild(ifr);
    }
    function checkHash(){
        var data = location.hash?location.hash.substring(1):'';
        if(data){
            //这里处理返回值
            alert(data);
            location.hash = '';
        }
    }
    setInterval(checkHash,1000);
    window.onload = sendRequest;
</script>
</body>
</html>
异域http://www.lamport.me/b.html
<!doctype html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>另某个域的:b.html</title>

<style type="text/css">

</style>
</head>

<body>
<script type="text/javascript">
function checkHash(){
    var data = '';
    //模拟一个简单的参数处理操作
    switch(location.hash){
        case '#sayHello':
              data = 'HelloWorld';
              break;
        case '#sayHi':
              data = 'HiWorld';
              break;
        default : break;
    }
    data && callBack('#'+data);
}
function callBack(hash){
   var proxy = document.createElement('iframe');
   proxy.style.display = 'none';
   proxy.src = 'http://localhost/c.html'+hash;
   document.body.appendChild(proxy);
}
window.onload = checkHash;
</script>
</body>
</html>
本地http://localhost/c.html
<!doctype html>
<html>
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    <title>localhost:c.html</title>
</head>

<body>
<script type="text/javascript">
    //因为c.html和a.html属于同一个域,所以可以通过改变其location.hash的值,可以通过parent.parent获取a.html的window对象
    parent.parent.location.hash = self.location.hash.substring(1);
</script>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读