javascript 关于window.open和cookie的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5702855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A question about window.open and cookie
提问by wong2
Say I have two apps, www.test.comand sub.test.com, now in sub.test.com, I create a window to load www.test.comwith codes like :
假设我有两个应用程序,www.test.com和sub.test.com,现在在sub.test.com 中,我创建了一个窗口来加载www.test.com,代码如下:
window.open('www.test.com');
So the window just popup and load www.test.comsuccessfully.
Then I set a cookie in sub.test.com, say "uname=wong2;domain=.test.com", I've learned that with set to domain=.test.com, all sites with domain test.com(such as www.test.com, aaa.test.com, test.com) can read the cookie.
所以窗口只是弹出并成功加载www.test.com。
然后我在sub.test.com 中设置了一个 cookie ,说"uname=wong2;domain=.test.com",我了解到设置为domain=.test.com,所有具有域test.com 的站点(例如www.test.com, aaa.test.com, test.com) 可以读取 cookie。
But when I try to load the cookie from the window that just popup with www.test.com, it can't get it.
但是当我尝试从刚刚弹出的窗口加载 cookie 时www.test.com,它无法获取它。
Then I found that if I don't use window.openbut directly open www.test.comin browser, it works.
然后我发现如果我不使用window.open而是直接在浏览器中打开www.test.com,它就可以工作。
So is there some restrictions on window.openand cookie?
那么window.open和cookie是否有一些限制?
采纳答案by ezmilhouse
just check how you set the cookie:
只需检查您如何设置 cookie:
var domain = 'test.com';
var expires = (function(days){
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
return date.toUTCString();
})(5);
var name = 'myCookie';
var path = '/';
var value = 'foo';
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expires + "; path='" + path + "'; domain=" + domain + ";";
回答by Karthik
That is called cross domain and you cant set cookie in one domain and try to access that in different domain. Browsers wont allow doing this.I think you can accomplish this using iframe or same origin policy or try using document.domainI am not sure what you want to do exactly.
这称为跨域,您不能在一个域中设置 cookie 并尝试在不同域中访问它。浏览器不允许这样做。我认为您可以使用 iframe 或同源策略来完成此操作,或者尝试使用 document.domain我不确定您想要做什么。

