1、概念html
2、如何使用(一些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; }
3、cookie、sessionStorage、localStorage 的區別服務器
---------------------------------------------------------------------------------------------------------------分割線---------------------------------------------------------------------------------------------------------------cookie
多說一點點 T^Tsession
cookie 如何防範XSS攻擊xss
XSS 是指攻擊者在返回的HTML中嵌入JS腳本,爲減輕這些攻擊,須要在HTTP頭部配上set-cookie: 函數
httponly: 這個屬性能夠防止XSS,由於他會禁止JavaScript腳原本訪問cookiespa
secure: 這個屬性告訴瀏覽器僅在請求爲https的時候發送cookiecode
挖個坑,詳細的cookie如何防範xss(2019/9/12)htm