IE下javascript cookie path
2010-06-13 09:22 smat 阅读(433) 评论(0) 编辑 收藏 举报发现居然和Javascript 设置 Cookie 时的 path 有关。IE下Cookie种在 /或者URL所在路径时正常,如果Cookie值作用域在当前URL下则IE下javascript 无法获取到设置的Cookie值。
var cookie_name = "name";
var cookie_value = "value";
expires = new Date();
expires.setTime(expires.getTime() + 86400 * 1000);
// 有Bug document.cookie无法独到cookie_name值
document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path="
+ window.location.pathname;
// 正常
document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path=/test/";
// 正常
document.cookie = "cookie_name=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path=/";
var cookie_value = "value";
expires = new Date();
expires.setTime(expires.getTime() + 86400 * 1000);
// 有Bug document.cookie无法独到cookie_name值
document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path="
+ window.location.pathname;
// 正常
document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path=/test/";
// 正常
document.cookie = "cookie_name=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path=/";
//IE Cookie Bug 替代方案
var cookie_path = window.location.pathname;
var cookie_name = encodeURIComponent(cookie_path.substring(cookie_path
.lastIndexOf('/') + 1));
cookie_path = cookie_path.substring(0, cookie_path.lastIndexOf('/') + 1);
var cookie_value = "value";
expires = new Date();
expires.setTime(expires.getTime() + 86400 * 1000);
document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path=" + cookie_path;
var cookie_path = window.location.pathname;
var cookie_name = encodeURIComponent(cookie_path.substring(cookie_path
.lastIndexOf('/') + 1));
cookie_path = cookie_path.substring(0, cookie_path.lastIndexOf('/') + 1);
var cookie_value = "value";
expires = new Date();
expires.setTime(expires.getTime() + 86400 * 1000);
document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; expires=" + expires.toGMTString() + "; path=" + cookie_path;
替代方案根据每个页面的URL文件名来做Cookie名,有效范围在当前页路经下。
如:url 等于 /test/test.html
则cookie名为test.html,有效路径为/test/
这样也可以做到同一个js部署在每个页面上能读到只对当前URL有效的cookie值。代价是当用户在同一级目录下访问很多页面时会导致cookie值不
断增大。结果是当前路径下的每个http请求都带很长一段的cookie,直接导致服务器接收客户端request的header长度增长,流量增长的同
时服务器负担也变重。而且根据 RFC 2109
的定义Cookie也有长度和个数限制,IE允许的最大 Cookie 长度是 4096 字节,允许50个
Cookie 名-值对。如果要突破50个名-值对的限制,可以在一个名-值使用Cookie字典的方式保存更多的Cookie变量。