Cookie的封装
封装Cookie
使用封装好的Cookie实现网站语言切换
Cookie.html页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Cookie的封装</title> <!-- <script src="../static/js/jquery-3.6.1.min.js" type="text/javascript" charset="utf-8"></script>--> <!-- <script src="../static/js/cookie.js" type="text/javascript" charset="utf-8"></script>--> </head> <body> <button id="cn">中文</button> <button id="en">英文</button> <script type="module"> // import{set,get,remove} from '../static/js/cookie'; // import {set,get,remove} from '../static/js/cookie.js'; // set('username','alex'); // set('username','zs'); // set('age',18); // set('用户名','张三'); // set('sex','male',{ // maxAge:30*24*3600, // }) // remove('username'); // remove('用户名') // console.log(get('username')); // console.log(get('age')); // console.log(get('用户名')); // console.log(get('sex')); // 使用封装好的Cookie实现网站语言切换 import {set} from '../static/js/cookie.js'; const cnBtn = document.getElementById('cn'); const enBtn = document.getElementById('en'); cnBtn.addEventListener( 'click', () => { set('language','cn',{ maxAge:30 * 24 * 3600 }); window.location = 'Cookie.html'; }, false ); enBtn.addEventListener( 'click', () => { set('language','en',{ maxAge:30 * 24 * 3600 }); window.location = 'Cookie.html'; }, false ); </script> </body> </html>
cookie.js文件
// 写入Cookie const set = (name,value, {maxAge,domain,path,secure} = {}) =>{ let cookieText = `${encodeURIComponent(name)}= ${encodeURIComponent(value)}`; if (typeof maxAge === 'number') { cookieText += `; max-age=${maxAge}`; } if (domain) { cookieText += `; domain=${domain}`; } if (path) { cookieText += `; path=${path}`; } if (secure) { cookieText += `; secure`; } document.cookie = cookieText; // document.cookie='username=alex; max-age=5; domain=' }; // 通过name获取cookie的值 const get = name => { name = `${encodeURIComponent(name)}`; const cookies = document.cookie.split('; ') for (const item of cookies) { const [cookieName,cookieValue] = item.split('='); if (cookieName === name) { return decodeURIComponent(cookieValue); } } return; }; // 'username=alex; age=18; sex=male' // ['username=alex', 'age=18', 'sex=male'] // ["username","alex"] // get('用户名'); // 根据name、domain和path删除Cookie const remove = (name,{domain,path} = {}) =>{ set(name,'',{domain,path,maxAge:-1}); }; export {set,get,remove};
Cookie的注意事项
前后端都可以写入和获取Cookie
Cookie有数量限制
每个域名下的Cookie数量有限
当超过单个域名限制之后,再设置Cookie,浏览器就会清除以前设置的Cookie
Cookie有大小限制
每个Cookie的存储容量很小,最多只有4KB左右
标签:domain,set,封装,name,get,Cookie,注意事项,cookie From: https://www.cnblogs.com/wsfj/p/17206051.html