JS : Javascript 如何获取 Cookie 值(含最简方法)

类别: JavaScript 阅读量:883

首页>文章>所有文章>JS : Javascript 如何获取 Cookie 值(含最简方法)

在 Javascript 中你可能有时需要访问 Cookie,获取 Cookie 值。

本文将介绍 JS 获取 Cookie 值的两种方法:

  • 自定义函数获取 Cookie 值

  • 使用第三方库获取 Cookie 值

自定义函数获取 Cookie 值

获取 Cookie 值的自定义函数,你只需把我们提供自定义函数复制到你的代码中:

functiongetCookie(name){letcookieValue=null;if(document.cookie&&document.cookie!==''){constcookies=document.cookie.split(';');for(leti=0;i<cookies.length;i++){constcookie=cookies[i].trim();// Does this cookie string begin with the name we want?if(cookie.substring(0,name.length+1)===(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}returncookieValue;}

使用该函数获取 Cookie 值,

constcookie_value=getCookie('cookie_name');

推荐使用该方法获取 Cookie 值,代码非常少,而且简单易用。

使用第三方库获取 Cookie 值

使用 js-cookie 第三方库获取 Cookie 值。

安装 js-cookie

npm install js-cookie

使用该库提供的函数获取 Cookie 值:

importCookiesfrom'js-cookie';constcookie_value=Cookies.get('cookie_name');

js-cookie 库源码

附 js-cookie 库 UMD 格式源码,可以直接复制到文件中,在浏览器加载后就可使用,方便那些不知怎么安装 js-cookie ,或无法访问 github 的用户:

/*! js-cookie v3.0.5 | MIT */;(function(global,factory){typeofexports==='object'&&typeofmodule!=='undefined'?module.exports=factory():typeofdefine==='function'&&define.amd?define(factory):(global=typeofglobalThis!=='undefined'?globalThis:global||self,(function(){varcurrent=global.Cookies;varexports=global.Cookies=factory();exports.noConflict=function(){global.Cookies=current;returnexports;};})());})(this,(function(){'use strict';/* eslint-disable no-var */functionassign(target){for(vari=1;i<arguments.length;i++){varsource=arguments[i];for(varkeyinsource){target[key]=source[key];}}returntarget}/* eslint-enable no-var *//* eslint-disable no-var */vardefaultConverter={read:function(value){if(value[0]==='"'){value=value.slice(1,-1);}returnvalue.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(value){returnencodeURIComponent(value).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};/* eslint-enable no-var *//* eslint-disable no-var */functioninit(converter,defaultAttributes){functionset(name,value,attributes){if(typeofdocument==='undefined'){return}attributes=assign({},defaultAttributes,attributes);if(typeofattributes.expires==='number'){attributes.expires=newDate(Date.now()+attributes.expires*864e5);}if(attributes.expires){attributes.expires=attributes.expires.toUTCString();}name=encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);varstringifiedAttributes='';for(varattributeNameinattributes){if(!attributes[attributeName]){continue}stringifiedAttributes+='; '+attributeName;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];}return(document.cookie=name+'='+converter.write(value,name)+stringifiedAttributes)}functionget(name){if(typeofdocument==='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.varcookies=document.cookie?document.cookie.split('; '):[];varjar={};for(vari=0;i<cookies.length;i++){varparts=cookies[i].split('=');varvalue=parts.slice(1).join('=');try{varfound=decodeURIComponent(parts[0]);jar[found]=converter.read(value,found);if(name===found){break}}catch(e){}}returnname?jar[name]:jar}returnObject.create({set,get,remove:function(name,attributes){set(name,'',assign({},attributes,{expires:-1}));},withAttributes:function(attributes){returninit(this.converter,assign({},this.attributes,attributes))},withConverter:function(converter){returninit(assign({},this.converter,converter),this.attributes)}},{attributes:{value:Object.freeze(defaultAttributes)},converter:{value:Object.freeze(converter)}})}varapi=init(defaultConverter,{path:'/'});/* eslint-enable no-var */returnapi;}));

结语

本文介绍了使用自定义函数获取 Cookie 值、使用第三方库获取 Cookie 值两种方法 获取 Cookie 值。

相关页面



评论

暂无评论,快来抢沙发吧~