如何确保可以从IE中的新窗口读取cookie?

时间:2012-11-13 22:15:35

标签: javascript jquery

我目前正在使用javascript并尝试通过cookie将sessionGUID传递给使用IE9的新打开的窗口。我希望避免将sessionGUID放在查询字符串上。

我使用以下代码打开新窗口并将cookie分配给新窗口:

var pathname = /msgViewer.htm?A=" + aGUID + "&Detached=yes"; 
var myWindow = window.open(pathname, "detached_window");
myWindow.document.cookie = "SG=" + sGUID;

但是,当(文档).ready在新窗口中执行时,似乎没有设置cookie。

$(document).ready(function () {
...
sGUID = getCookie("SG");
...
[call to AJAX webservice that requires sGUID be passed]

...

    function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

当我在getCookie调用之后设置(测试)警报时,sGUID未定义,但警报引起的延迟(用户输入)允许在此之后读取cookie。

如何在$(document).ready执行之前确保在新窗口中设置cookie? ...或者至少确保在从cookie中检索sessionGUID之前未调用webservice?

FireFox或Chrome浏览器中不存在此问题。

提前致谢,供您考虑......

更新(20121115): 此链接http://ellislab.com/forums/viewthread/220241/表示在页面请求完成之前,cookie数据可能无法使用。上述方案通常仅在初始登录期间或删除cookie之后发生(并且仍然是间歇性的)我当前的解决方案/解决方法是打开和关闭临时窗口并重新检索cookie。由于无论如何在新窗口打开时都会出现问题,因此额外的窗口闪烁不明显。我还在$(document).ready函数之外移动了cookie的检索。 这是附加代码:

sGUID = getCookie("SG");
if (sGUID == null) {
    var jwURL = "/Test.htm";
    jw = window.open(jwURL, "junk_window",width=1,height=1);
    jw.close();
    sGUID = getCookie("SG");
}

1 个答案:

答案 0 :(得分:0)

“更新20121115”(打开/关闭临时窗口)确实解决了我的问题。我最终使用了一个不同的getCookie函数来检索cookie - 但这与我最初的问题没有直接关系:

   function getCookie(c_name) {
        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 == c_name) {
                return unescape(y);
            }
        }
    }