原文地址:https://www.toymoban.com/diary/js/41.html
原生JS设置、删除、获取Cookie
<script> /* * 设定Cookie值 */ function setCookie(cookieName, value, msToExpire, path, domain, isSecure) { var expiryDate; // 相对到期时间(以毫秒为单位) if (msToExpire) { expiryDate = new Date(); expiryDate.setTime(expiryDate.getTime() + msToExpire); } document.cookie = cookieName + '=' + window.encodeURIComponent(value) + (msToExpire ? ';expires=' + expiryDate.toGMTString() : '') + ';path=' + (path || '/') + (domain ? ';domain=' + domain : '') + (isSecure ? ';secure' : ''); } /* * 获取Cookie值 */ function getCookie(cookieName) { var cookiePattern = new RegExp('(^|;)[ ]*' + cookieName + '=([^;]*)'), cookieMatch = cookiePattern.exec(document.cookie); return cookieMatch ? window.decodeURIComponent(cookieMatch[2]) : 0; } /* * 删除Cookie值 */ function deleteCookie(cookieName, path, domain) { setCookie(cookieName, '', -86400, path, domain); } <script>