代码改变世界

JS 获取跨域的cookie.

2012-12-27 16:46  chris-shao  阅读(2770)  评论(2编辑  收藏  举报

JS 获取跨域cookie? 简直是疯了。这怎么可能,不过在条件允许的情况下(两个域内文件都可以自定义),如下有一个方案。

一共需要3个文件,第一个文件为需要获取cookie的页面,在这个页面内嵌入存在网站B的获取cookie的代码,

第二个文件存在网站B,读取cookie,然后将自身URL修改为网站A域下,并将cookie拼接到URL中,

第三个文件在网站A,用于调用父页面处理得到的cookie.

 

代码如下:

 

文件一:假设为网站A下.1.html

<html>
<head>
</head>
<body>
<iframe src='http://B.com/2.html' width='100' height='100'>
</iframe>
<textarea id="sogou_cookie">
</textarea>

</body>
</html>

 

文件二:存在网站B下,名为2.html

<html>
<head>
</head>
<body>
<script>
window.location="http://A.com/3.html?"+document.cookie;
</script>
</body>
</html>

 

文件三:存在网站A下:

<html>
<head>
</head>
<body>
<script>
window.parent.document.getElementById("sogou_cookie").value=window.location.toString().substring(window.location.toString().indexOf("?"));
</script>
</body>
</html>

这样,当打开1.html时,文本框中内容就为B站的所有cookie了。