JS獲取跨域的cookie例項

microsoft_kk發表於2015-04-17

如果說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了。

相關文章