我搜索了我的要求並找到了我的問題的答案。但我無法使它工作。因此我想在這裏發佈我的要求。來自跨域的Cookie無法在iframe中訪問
我的網站由第三方供應商託管,我無法控制他們的服務器。 我有一個iframe設置在他們的一個html頁面。這個iframe將指向我的服務器,我應該能夠訪問供應商在其主頁中設置的cookie。爲了嘗試這個,我創建了兩個html頁面。一個將被命名爲SetCookie.html,另一個將被命名爲GetCookie.html。兩者都駐留在不同的計算機中。請從下面的源代碼:
SetCookie.html
<html>
<head>
<title>Set Cookie</title>
</head>
<body>
<script type="text/javascript">
function setCookie() {
var cookieValue = document.getElementById("txtCookie").value;
var cookieName = "TestCookie";
document.cookie = cookieName + "=" + cookieValue;
document.getElementById("tdCookieMessage").innerHTML = cookieName + "=" + cookieValue + " is set!";
}
</script>
<table>
<tr>
<td>
Cookie
</td>
<td>
<input type="text" id="txtCookie" value="" />
</td>
<td>
<input type="button" id="btnGetCookie" onclick="setCookie();" value="Set Cookie!" />
</td>
</tr>
<tr>
<td colspan="3" id="tdCookieMessage">
</td>
</tr>
</table>
<table>
<tr>
<td>
<iframe src="http://myServer/GetCookie.html"></iframe>
</td>
</tr>
</table>
</body>
</html>
GetCookie.html
<html>
<head>
<title>Get Cookie</title>
<script type="text/javascript">
function getCookie(cookieName) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookieName) {
document.getElementById("tdCookie").innerHTML = unescape(y);
expireCookie(cookieName);
}
}
}
function expireCookie(cookieName) {
document.cookie = cookieName + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input type="button" id="btnGetCookie" onclick="getCookie('TestCookie');" value="Test Cookie Value is: " />
</td>
<td id="tdCookie">
</td>
</tr>
</table>
</body>
</html>
任何建議表示讚賞。
只有爲頁面所在域設置的cookie纔會被髮送到頁面。 IE你在mywebsite.com上,他們在他們的domain.com上,你不會收到他們的cookies,他們也不會收到你的cookies。 – 2012-07-11 20:23:04