我搜索了我的要求并找到了我的问题的答案。但我无法使它工作。因此我想在这里发布我的要求。来自跨域的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