文章目录

  • 一、converter.mjs 文件
  • 二、assign.mjs 文件
  • 三、api.mjs 文件

一、converter.mjs 文件

作用:中文/二进制 url编码/解码

/* eslint-disable no-var */// 模块功能:url编码/解码// 1-JS全局函数 /**函数名称:encodeURIComponent(uri)函数功能:把字符串作为 URI 组件进行编码参数:uri 必须,一个字符串,含有 URI 组件或其他要编码的文本返回值:URI字符串说明:该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) *//**函数名称:decodeURIComponent(uri) 函数功能:对 encodeURIComponent() 函数编码的 URI 进行解码参数:uri 必需,一个字符串,含有编码 URI 组件或其他要解码的文本说明:编码特点 %[\dA-F]{2}*/// 2-url构成/**网页地址实例: http://www.runoob.com/html/html-tutorial.html语法规则: scheme://host.domain:port/path/filenamescheme:因特网服务的类型。最常见的类型是 httphost:域主机(http 的默认主机是 www)domain:因特网域名,比如 runoob.com:port:主机上的端口号(http 的默认端口号是 80)path:服务器上的路径(如果省略,则文档必须位于网站的根目录中)filename:文档/资源的名称*/export default {/**函数名称:converter.read(value)函数功能:uri解码参数:value 必需,要取得的Cookie名称说明:*/read: function (value) {if (value[0] === '"') {value = value.slice(1, -1)}return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)},/**函数名称:converter.write(value)函数功能:uri编码参数:value 必需说明:*/write: function (value) {return encodeURIComponent(value).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}
}/* eslint-enable no-var */

二、assign.mjs 文件

作用:分割 Cookie 键值对字符串

/* eslint-disable no-var *//**函数名称:function (target)函数功能:Cookie字符串分割参数:target 必需,要分割的Cookie名称返回值:target[key]说明:浅层遍历args,并分别返回各参数*/
export default function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i]for (var key in source) {target[key] = source[key]}}return target
}
/* eslint-enable no-var */

三、api.mjs 文件

作用:定义 cookie 功能函数

/* eslint-disable no-var */
import assign from './assign.mjs'
import defaultConverter from './converter.mjs'// 1-知识点Cookie  -4B/**属性:Cookie 是不可以跨域名name: value: Expires: 有效期,单位s;domain: 域名,解决跨域问题。Cookie是不可以跨域名的;path: 允许访问Cookie的路径,默认情况下,cookie 属于当前页面。数据存储格式:Cookie 以名/值对形式存储  *字符串*示例:username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/存储/获取:document.cookie返回格式: 字符串cookie总结:cookie 在过期时间之前一直有效,即使窗口或浏览器关闭浏览器也会在每次请求的时候 *主动组织* 所有域下的cookie到请求头 cookie 中,发送给服务器端浏览器会 *主动存储* 接收到的 set-cookie 头信息的值可以设置 http-only 属性为 true来禁止客户端代码(js)修改该值可以设置有效期 (默认浏览器关闭自动销毁)(不同浏览器有所不同)同域下个数有限制,最好不要超过50个(不同浏览器有所不同)单个cookie内容大小有限制,最好不要超过4000字节(不同浏览器有所不同)应用场景:保存用户登录状态;跟踪用户行为。如:购物车*/// 2-知识点Storage  -5MB/**localStorage:*永久存储* 在本地硬盘的数据中,生命周期是永久(除非手动删除)属性:key: value: 数据存储格式:*字符串* (auto)<script>localStorage.setItem('name', '张三')localStorage.age = 18localStorage['sex'] = '男'localStorage.obj = JSON.stringify({ name: '小明' })console.log(localStorage.name)  //张三console.log(localStorage.getItem('age'));   //18console.log(localStorage['sex'])        //男console.log(JSON.parse(localStorage.obj))   //{name: "小明"}localStorage.removeItem('age')console.log(localStorage.age);  //undefinedconsole.log(localStorage.key(0));   //objconsole.log(localStorage.key(1));   //nameconsole.log(localStorage.key(2));   //sex// window.localStorage.clear()// console.log(localStorage);   //Storage {length: 0}</script>sessionStorage:*临时存储* 在浏览器中,生命周期为浏览器页面打开时间(页面关闭时数据丢失)属性:key: value: 数据存储格式:*字符串* (auto)两者通用属性和方法:setItem(keyname,value) 存储键值对,如果键名相同,则更新值getItem(keyname) 根据键名查找对应的值key(n) 返回第n个键的名称length 返回键键值对的数量(存储了几个不同的数据)removeitem(keyname) 根据键名删除对应的键值对clear() 清除所有键*/// 2-init 方法 初始化
function init (converter, defaultAttributes) {/**函数名称:set (name, value, attributes)函数功能:保存Cookie参数:attributes 可选项,格式为对象返回值:说明:*/function set (name, value, attributes) {// 没有document 直接return 返回什么也不执行if (typeof document === 'undefined') {return}// 把传入的值和默认值合并到一起,如果key一样,传入的值直接替换默认值attributes = assign({}, defaultAttributes, attributes)// 如果传入expires为天数,时间则直接转换为毫秒if (typeof attributes.expires === 'number') {attributes.expires = new Date(Date.now() + attributes.expires * 864e5)}// 把日期转为字符串设置cookie过期时间if (attributes.expires) {attributes.expires = attributes.expires.toUTCString()}// 对汉字编码进行处理name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape)var stringifiedAttributes = ''
// 遍历传入的对象并拼接属性值for (var attributeName in attributes) {// 为空字符串或者null undefined退出本次循环if (!attributes[attributeName]) {continue}stringifiedAttributes += '; ' + attributeName// 传入boolean值退出当前循环if (attributes[attributeName] === true) {continue}// Considers RFC 6265 section 5.2:// ...// 3.  If the remaining unparsed-attributes contains a %x3B (";")//     character:// Consume the characters of the unparsed-attributes up to,// not including, the first %x3B (";") character.// ...stringifiedAttributes += '=' + attributes[attributeName].split(';')[0]}// 写入的时候使用converter进行encode编码return (document.cookie =name + '=' + converter.write(value, name) + stringifiedAttributes)}// get 方法 读取cookiefunction get (name) {if (typeof document === 'undefined' || (arguments.length && !name)) {return}// To prevent the for loop in the first place assign an empty array// in case there are no cookies at all.var cookies = document.cookie ? document.cookie.split('; ') : []var jar = {}for (var i = 0; i < cookies.length; i++) {var parts = cookies[i].split('=')var value = parts.slice(1).join('=')try {var found = decodeURIComponent(parts[0])jar[found] = converter.read(value, found)if (name === found) {break}} catch (e) {}}return name ? jar[name] : jar}// 返回 新创建的对象return Object.create({set: set, // 设置cookie方法get: get, // 读取cookie方法remove: function (name, attributes) {
// 删除cookie方法,其实内部调用了set方法,并把expirse设置为过去时间来删除set(name, '',assign({}, attributes, {expires: -1}))},// 修改设置cookie的一些常用属性类似于path,domain,expires, 重新返回一个实例化的对象,
// 可以设置一个全局的cookie共享设置的一些属性值withAttributes: function (attributes) {return init(this.converter, assign({}, this.attributes, attributes))},// 和上个方法作用差不多,可以对converter,进行一些扩展withConverter: function (converter) {return init(assign({}, this.converter, converter), this.attributes)}},// Object.create的可选值,新增一些对象上的属性,
// Object.freeze冻结对象不能删除和修改另外不能修改该对象已有属性的可枚举性、可配置性、可写性,
// 以及不能修改已有属性的值{attributes: { value: Object.freeze(defaultAttributes) },converter: { value: Object.freeze(converter) }})
}export default init(defaultConverter, { path: '/' })
/* eslint-enable no-var */

Cookie.js 源码解析相关推荐

  1. js怎么调用wasm_Long.js源码解析

    基于现在市面上到处都是 Vue/React 之类的源码分析文章实在是太多了.(虽然我也写过 Vite的源码解析 所以这次来写点不一样的.由于微信这边用的是 protobuf 来进行 rpc 调用.所以 ...

  2. 【Vue.js源码解析 一】-- 响应式原理

    前言 笔记来源:拉勾教育 大前端高薪训练营 阅读建议:建议通过左侧导航栏进行阅读 课程目标 Vue.js 的静态成员和实例成员初始化过程 首次渲染的过程 数据响应式原理 – 最核心的特性之一 准备工作 ...

  3. js define函数_不夸张,这真的是前端圈宝藏书!360前端工程师Vue.js源码解析

    优秀源代码背后的思想是永恒的.普适的. 这些年来,前端行业一直在飞速发展.行业的进步,导致对从业人员的要求不断攀升.放眼未来,虽然仅仅会用某些框架还可以找到工作,但仅仅满足于会用,一定无法走得更远.随 ...

  4. JavaScript数字运算必备库——big.js源码解析

    概述 在我们常见的JavaScript数字运算中,小数和大数都是会让我们比较头疼的两个数据类型. 在大数运算中,由于number类型的数字长度限制,我们经常会遇到超出范围的情况.比如在我们传递Long ...

  5. video.js 源码解析

    为什么80%的码农都做不了架构师?>>>    写在前面 现在视频业务越来越流行了,播放器也比较多,作为前端工程师如何打造一个属于自己的播放器呢?最快最有效的方式是基于开源播放器深度 ...

  6. 如何将文件地址转为url_Node.js 源码解析 util.promisify 如何将 Callback 转为 Promise

    Nodejs util 模块提供了很多工具函数.为了解决回调地狱问题,Nodejs v8.0.0 提供了 promisify 方法可以将 Callback 转为 Promise 对象. 工作中对于一些 ...

  7. connect.js源码解析

    前言 众所周知,connect是TJ大神所造的一个大轮子,是大家用尾式调用来控制异步流程时最常使用的库,也是后来著名的express框架的本源.但令人惊讶的是,它的源码其实只有200多行,今天也来解析 ...

  8. 【Vue.js源码解析 三】-- 模板编译和组件化

    前言 笔记来源:拉勾教育 大前端高薪训练营 阅读建议:建议通过左侧导航栏进行阅读 模板编译 模板编译的主要目的是将模板 (template) 转换为渲染函数 (render) <div> ...

  9. addEvent.js源码解析

    露露 前言: 看两三遍即可. 在看 jQuery 源码时,发现了这段注释: //源码5235行 /* * Helper functions for managing events -- not par ...

  10. 史上最全的vue.js源码解析(四)

    虽然vue3已经出来很久了,但我觉得vue.js的源码还是非常值得去学习一下.vue.js里面封装的很多工具类在我们平时工作项目中也会经常用到.所以我近期会对vue.js的源码进行解读,分享值得去学习 ...

最新文章

  1. 活着不易,5G时代终端厂商的路在何方?
  2. 教你学会Sql中 ROW_NUMBER的用法
  3. java pdf表单域实现_Java 创建PDF表单域 - 文本框、复选框、列表框、组合框、按钮等...
  4. Android之解决TabLayout里面每个Tab项的间距和修改指示线的长度(非反射)和修改选中字体大小
  5. linux下网口监控软件_超赞的!Aibaba技术官分享高性能Linux服务器解读笔记
  6. windows做ntp server,linux做ntp client端的配置方法
  7. java转动的风扇课程设计,课程设计—智能风扇设计报告
  8. h3c trunk口改access_H3C交换机恢复出厂和各种基本配置
  9. 手机壳定制商城小程序系统 手机壳定制商城小程序源码
  10. 1.5多媒体技术的应用领域
  11. 如何添加使用微信小程序,教程在这里,微信小程序怎样添加使用
  12. 用大数据看懂《速度与激情》的用车法则
  13. 远程手机教学|简单实用,1键远程协助老人使用智能手机
  14. 快速复制粘贴小工具txmouse
  15. 85D - Sum of Medians
  16. 树莓派麦克风杂音问题…待解决
  17. 怎样搭建自己的网站,如何利用花生壳建立个人简易静态网站?
  18. 在存储过程中调用execute immediate 执行 create table语句报TBR-17004: Permission denied
  19. 软工实践第二次作业-黄紫仪
  20. 使用ThinkJs搭建微信中控服务

热门文章

  1. e4a java_易安卓e4a编译生成R.java文件失败的解决办法
  2. 计算机存储溢出 是什么意思,数据溢出是什么意思
  3. 九州海上牧云记,电视剧节奏太慢?教你如何看全集
  4. 【Leetcode】1101. The Earliest Moment When Everyone Become Friends
  5. MBTI职业性格测试 测评报告
  6. Java的高级篇--JDK8的新特性
  7. 如果我们遇上得州寒潮,会不会「悲剧」?
  8. spring boot UnsatisfiedDependencyException:
  9. 毕业生的档案都有什么意义,为什么说它那么重要|智测优聘总结
  10. 【STM32】几款常用产品(F1、F4、F7)的区别