Internet Explorer不允许我使用这个Javascript函数创建会话cookie

Internet Explorer won't let me create session cookie using this Javascript function?

本文关键字:函数 Javascript 创建 会话 cookie 不允许 Explorer 允许我 Internet      更新时间:2023-09-26

我正在使用Javascript创建cookie,如下所示

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

Firefox和Chrome为7天创建mcoo cookie,为SESSION创建mdes cookie,而Internet Explorer只创建mcoo cookie。我遗漏了什么?

    createCookie('mcoo', hash, 7);
    createCookie('mdes', hash);

作为解决方案,我已将天* 24更改为6,并将mcoo的到期日期更改为28(因此这是1周),并将到期日期更改为模式1(6小时)。

当你发现…IE的工作是不同的(又一次,奇怪的是吗?)

给出ZERO值过期,将在firefox &chrome,而不是IE,因为在IE中,cookie一旦设置就会立即过期。

所以…

FF,克雷格:

document.cookie = name + "=" + value + " expires=0; path=/";

…为了在IE中工作,您需要删除expire参数,并保留如下:

即:

document.cookie = name + "=" + value + " ; path=/";

更新

我可能会用这样的东西:
edit:在IE11上测试并运行&&CR36

function createCookie(name, value, days) {
    var c_date,
    c_name = name + "=" + value + ";",
    c_expi = "",
    c_path = "path=/";
    if (days > 0) {
        c_date = new Date();
        c_date.setTime(c_date.getTime() + (days * 24 * 60 * 60 * 1000));
        c_expi = "expires=" + c_date.toGMTString() + ";";
    }
    // create the cookie
    document.cookie = c_name + c_expi + c_path;
}

然后调用函数:

// normal cookie expire in 7 days
createCookie('mcoo', hash, 7);
// session cookie
createCookie('mdes', hash, 0);

来源:通过JavaScript设置Session Only Cookie
更多:Session only cookies with Javascript