如何使用 javascript 设置 cookie 的 HttpOnly 标志?
我正在尝试创建一个 cookie,并启用 HttpOnly 标志。
虽然似乎有大量关于如何在 Java 和 .Net 中执行此操作的资源,但我需要在 javascript 中执行此操作。
这是我的(目前失败的)功能
createCookie = function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; domain=my.domain.com; path=/; HttpOnly;";
谢谢 -
I'm trying to create a cookie, with the HttpOnly flag enabled.
While there seems to be a plethora of resources about how to do it in Java and .Net, I need to do it in javascript.
Here is my (currently failing) function
createCookie = function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; domain=my.domain.com; path=/; HttpOnly;";
Thanks -
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法在 JavaScript 中访问 HttpOnly cookie。
以下引文借用自维基百科资料:
换句话说,HttpOnly cookie 只在服务器端使用。
我用 PHP 编写了一个示例:
它会提醒
foo=bar
。删除 cookie,将
$isHttpOnly
更改为true
,重新加载页面,您将看到一个空警报。但同时浏览器会存储 cookie,以便在向服务器发出请求时将其发送。You cannot access an HttpOnly cookie in JavaScript.
The following quotation is borrowed from the Wikipedia material:
In other words, HttpOnly cookies are made to be used only on the server side.
I wrote an example in PHP:
It alerts
foo=bar
.Remove the cookie, change
$isHttpOnly
totrue
, reload the page, and you'll see an empty alert. But at the same time the browser stores the cookie to send it during a request to the server.