问题
I have the following code in website1.com:
<script type="text/javascript">
document.cookie = "qwe=1";
alert(document.cookie);
</script>
and website2.com contains:
<iframe src="http://website1.com"></iframe>
When I open the page website2.com in IE it alerts empty string (if no cookies was set before).
Other browsers alert "qwe=1".
So the question is why and how to workaround this?
回答1:
It is about security in IE.
If you want allow access to cookies in IFRAME, you should set HTTP header as follows:
ASP.NET:
HttpContext.Current.Response.AddHeader("p3p","CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
JSP:
response.addHeader("P3P","CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"")
PHP:
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
回答2:
Cookies are set with document.cookie
, however they are not sent to the server (and therefore have no effect there) until the next pageload. I would assume that standard behaviour of document.cookie
is to mimic this and not update the read value until the next pageload (in other words, setting document.cookie
sets a cookie, but reading document.cookie
gives the cookies that were sent in the request).
IE9 fixed a lot of issues present in older versions. And I mean a LOT. This is most likely one of them. The workaround, I would imagine, is handling cookies yourself. Just as in PHP I have the function:
<?php
function setRealCookie( ... ) {
setcookie( ... );
$_COOKIE[...] = ...;
}
?>
In JavaScript you could create an object that keeps track of cookies for you, including updating itself when a cookie is set and so on. Something like:
(cookies = {
data: {},
init: function() {
var c = document.cookie.split(";"), l = c.length, i, t;
for( i=0; i<l; i++) {
t = c[i].split("=");
cookies.data[t.shift()] = t.join("=");
}
},
read: function(key) {
return cookies.data[key];
},
set: function(key,value) {
document.cookie = key+"="+value;
cookies.data[key] = value;
}
}).init();
Then you can set a cookie with cookies.set("qwe","1");
and read it back with cookies.read("qwe");
.
来源:https://stackoverflow.com/questions/8061450/cookies-cannot-be-set-in-ie