您当前的位置: 首页 > 

彭世瑜

暂无认证

  • 2浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

js在浏览器中对cookie进行增删改查

彭世瑜 发布时间:2019-11-06 14:51:05 ,浏览量:2

Cookie格式
=; ; 

eg:
id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

属性

属性名说明默认值作用域Expires到期时间:UTC--Max-Age到期时间:秒 优先级高于Expires--domain所属域名当前域名默认当前域名, 指定值后是当前域名和子域名path生效的路径当前网址当前路径及其子路径HttpOnly无法通过 JavaScript 脚本拿到--Secure只有在加密协议 HTTPS 下生效--

特殊说明:

  1. 如果不添加过期时间,cookie 在浏览器关闭时删除
  2. 两个网址只要域名相同和端口相同,就可以共享 Cookie
  3. 使用document.cookie无法读取到与HTTPOnly属性的cookie
  4. 只能读取到cookie的键-值,没有办法读取属性的值
Cookie读写操作

如果本地html文件用浏览器打开页面会报错

A cookie associated with a cross-site resource at  was set without the `SameSite` attribute. 
A future release of Chrome will only deliver cookies with cross-site requests 
if they are set with `SameSite=None` and `Secure`.

可以使用Flask 搭建测试环境

# -*- coding: utf-8 -*-
from flask import Flask, send_file

app = Flask(__name__)


@app.route("/")
def get_info():
    return send_file("templates/index.html")


if __name__ == '__main__':
    app.run(debug=True)

JavaScript读写Cookie

// 创建Cookie 可以连续赋值,不会被覆盖
document.cookie="username=Tom";
document.cookie="age=12";

// 修改Cookie
document.cookie="username=Jack";

// 获取Cookie
console.log(document.cookie);
// age=12; username=Jack

// 删除  设置 expires 参数为以前的时间
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

可以自己封装函数处理cookie 例如:https://www.runoob.com/js/js-cookies.html

也可以使用插件读取 js-cookie: https://www.npmjs.com/package/js-cookie

参考

  1. https://segmentfault.com/a/1190000016372516
  2. 阮一峰 JavaScript 教程/浏览器模型/Cookie
关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0894s