标签:color indexof 获取 区别 tco 头部 clear time 一个
一、概念
二、如何使用(一些API和常见用法)
document.cookie = ‘username=Doe‘; // 基本设置 document.cookie = ‘username=Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT‘; // 基本设置 + 过期时间(默认情况下cookie在浏览器关闭时删除)
var x = document.cookie; // 读取cookie
// 给key重新赋值即可,例如原来的username=Doe,修改为John document.cookie = ‘username=John‘;
function getCookie(cname){ var name = cname + ‘=‘; var ca = document.cookie.split(‘;‘); for(var i = 0; i < ca.length; i++){ var c = ca[i].trim(); // trim()用于除去前后空格 if(c.indexOf(name) == 0) return c.substring(name.length, c.length); } return ‘‘; }
// 检测cookie中是否有我们想要得数据,可以使用getCookie函数(上面那个↑ function checkCookie() { var username = getCookie(‘username‘); if(username == ‘‘){ alert(‘welcome‘); } else { username = prompt(‘Please enter your name:‘, ‘‘); if(username != ‘‘ && username != null){ setCookie(‘username‘, username, 365); } } } // 设置cookie function setCookie(key, value, time){ var d = new Date(); d.setTime(d.getTime() + (time * 24 * 60 * 60 * 1000)); var expires = ‘expires=‘ + d.toGMTString(); document.cookie = key + ‘=‘ + value + ";" + expires; }
localStorage.setItem(key, value);
localStorage.getItem(key);
localStorage.removeItem(key);
localStorage.clear();
function getAll() { var valueArr = [];
var keyArr = []; for(var i = 0; i < localStorage.length; i++){ var key = localStorage.getKey(i);
keyArr.push(key); valueArr.push(localStorage.getItem(key); } return newArr; }
三、cookie、sessionStorage、localStorage 的区别
---------------------------------------------------------------------------------------------------------------分割线---------------------------------------------------------------------------------------------------------------
多说一点点 T^T
cookie 如何防范XSS攻击
XSS 是指攻击者在返回的HTML中嵌入JS脚本,为减轻这些攻击,需要在HTTP头部配上set-cookie:
httponly: 这个属性可以防止XSS,因为他会禁止JavaScript脚本来访问cookie
secure: 这个属性告诉浏览器仅在请求为https的时候发送cookie
挖个坑,详细的cookie如何防范xss(2019/9/12)
cookie,localStorage,sessionStorage的区别
标签:color indexof 获取 区别 tco 头部 clear time 一个
原文地址:https://www.cnblogs.com/pingzi-wq/p/11509746.html