在iFrame中设置无域cookie

时间:2014-08-19 12:05:18

标签: javascript iframe cookies subdomain

我有一个网站设置了一个cookie,让我们说 www.domain.com 名为 aCookie 。需要从其他子域检索此Cookie,因此我将Cookie的域设置为 .domain.com

我需要从链接到 sub.domain.com 的iFrame读取和编写Cookie。它们位于同一个域中,因此不存在跨站点限制或任何类型的限制。

奇怪的是,如果我在www.domain.com上编写cookie然后尝试从sub.domain.com更改它的值,则会创建第二个使用相同名称但使用域集的cookie到sub.domain.com,即使我明确地将域设置为.domain.com。

在这种情况发生后,奇怪的事情开始了,因为它不会被读取,或者它将被设置在其中一个cookie上但是从另一个cookie中读取。

知道为什么会发生这种情况以及如何解决它,谢谢?

Cookie.Set("directDepositMethod", directDepositMethod, { expires: 1, secure: true, path: '/', domain: ".domain.com" });

其中set:

 if (typeof value != "undefined") { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = String.Empty;
                options.expires = -1;
            }
            var expires = String.Empty;
            if (options.expires && (typeof options.expires == "number" || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == "number") {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = "; expires=" + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? "; path=" + (options.path) : "";
            var domain = options.domain ? "; domain=" + (options.domain) : "";
            var secure = options.secure ? "; secure" : "";
            document.cookie = [name, "=", encodeURIComponent(value), expires, path, domain, secure].join("");
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != String.Empty) {
                var cookies = document.cookie.split(";");
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + "=")) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

0 个答案:

没有答案