js操作获取和设置cookie

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js操作获取和设置cookie相关的知识,希望对你有一定的参考价值。

//创建cookie
function setCookie(name, value, expires, path, domain, secure) 
    var cookieText = encodeURIComponent(name) + ‘=‘ + encodeURIComponent(value);
    if (expires instanceof Date) 
        cookieText += ‘; expires=‘ + expires;
    
    if (path) 
        cookieText += ‘; expires=‘ + expires;
    
    if (domain) 
        cookieText += ‘; domain=‘ + domain;
    
    if (secure) 
        cookieText += ‘; secure‘;
    
    document.cookie = cookieText;

 
//获取cookie
function getCookie(name) 
    var cookieName = encodeURIComponent(name) + ‘=‘;
    var cookieStart = document.cookie.indexOf(cookieName);
    var cookieValue = null;
    if (cookieStart > -1) 
        var cookieEnd = document.cookie.indexOf(‘;‘, cookieStart);
        if (cookieEnd == -1) 
            cookieEnd = document.cookie.length;
        
        cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    
    return cookieValue;

 
//删除cookie
function unsetCookie(name) 
    document.cookie = name + "= ; expires=" + new Date(0);

原文地址:https://github.com/hawx1993/Front-end-Interview-questions

以上是关于js操作获取和设置cookie的主要内容,如果未能解决你的问题,请参考以下文章

js封装Cookie操作 js 获取cookie js 设置cookie js 删除cookie

js操作cookie

如何用js来操作cookie呢?

jquery cookie操作为什么去不到cookie值呢?

使用vue-cookies操作cookie

js操作cookie简单封装