我知道可以允许其他域读取我们的域 cookie,只要它们是 子域 属于同一个父域。
例如,intranet.abc.com
和 extranet.abc.com
可以通过将 domain 属性指定为 .abc.com
来允许彼此读取 cookie
现在,我真的需要允许其他域读取我的域 cookie(它们是 而不是同一域的子域 )。我在网上搜索了很多讨论=> 都说 “否”由于安全问题。我不确定我是否错过了解决方案,因为在这种情况下我没有看到任何安全问题。我的服务器很明显允许 此 cookie 将由 读取XYZ.COM 域,因为 cookie 不包含任何敏感信息,并且 XYZ.COM 域是我信任的域,
在我看来,应该有一种方法可以指定允许读取我们域中的特定 cookie 的其他域列表 ,就像 CORS 一样,服务器可以决定信息是否应该对某些受信任的域可用。
请告诉我是否可以不使用解决方法,如果可以,该怎么做?
如果不可能,我真的很想知道为什么。
关于我正在实现的一些信息:
我正在实现文件下载,在客户端我需要通过使用 javascript 中的间隔定期检查 cookie 中的下载 token 来检测下载是否完成。
我目前正在处理的当前系统的逻辑可能会将文件存储在 2 个不同的服务器中。如果当前服务器中缺少文件,它将在另一个服务器(另一个域)中下载文件
非常感谢。
最佳答案
您可以通过打开一个 iframe 到另一个域上的特殊检测页面并使用 window.postMessage API 在窗口之间进行通信来读取域外 cookie。显然,只有 HTML5。
为了简洁起见,稍微简化了 postMessage API,请参阅 MDN 开发人员页面以获取完整的详细信息。
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
<iframe id="ifrm" src="http://other.domain.com/getCookie.html"></iframe>
<script>
var iframe = document.getElementById('ifrm');
window.addEventListener('message', function (e) {
if (e.source === iframe.contentWindow && e.origin === 'other.domain.com') {
var cookie = e.data;
//do something with cookie
}
});
//wait for the iframe to load...maybe ping it first...then
iframe.contentWindow.postMessage('give me the cookie:cookie name', 'other.domain.com');
</script>
/* in getCookie.html */
<script>
window.addEventListener('message', function (e) {
if (e.origin === 'your.domain.com') {
var soughtCookie = /give me the cookie\:(.*)/.exec(e.data)[1];
// read the cookie
var cookie = getCookieFn(soughtCookie)
e.source.postMessage(cookie.toString(), 'your.domain.com');
}
}, false);
</script>
关于javascript - 与其他域共享 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20990704/