admin管理员组

文章数量:1334133

I have the following code in website1:

<script type="text/javascript">
    document.cookie = "qwe=1";
    alert(document.cookie);
</script>

and website2 contains:

<iframe src=""></iframe>

When I open the page website2 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?

I have the following code in website1.:

<script type="text/javascript">
    document.cookie = "qwe=1";
    alert(document.cookie);
</script>

and website2. contains:

<iframe src="http://website1."></iframe>

When I open the page website2. 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?

Share Improve this question edited Nov 9, 2011 at 10:20 tsds asked Nov 9, 2011 at 7:02 tsdstsds 9,04914 gold badges64 silver badges85 bronze badges 1
  • 1 header('P3P: CP="CAO PSA OUR"'); – Sam Becker Commented Nov 9, 2011 at 10:16
Add a ment  | 

2 Answers 2

Reset to default 5

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"');

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");.

本文标签: javascriptCookies cannot be set in IEStack Overflow