当前位置:网站首页>JS operation cookie, JS setting cookie value, JS reading cookie value

JS operation cookie, JS setting cookie value, JS reading cookie value

2022-06-21 07:05:00 Just a craftsman

js Yes Cookie The operation of

Preface :

​ Here is a brief introduction to the use of java Yes Cookie How to operate , But it is not recommended to use Cookie, Because some users will disable the website Cookie, If used improperly, users will not be able to use the website , So for Cookie Give a brief introduction , Understanding is good. .

js Function usage

// Set up Cookie Name and value in and expiration time 【 Company : God 】
Cookie.set("page", page, 100)

// obtain Cookie The value in 
var page = Cookie.get("page");

// remove Cookie
Cookie.remove("page");

js function

var Cookie = {
    
    set: function (key, value, exdays) {
    
        // check Key, key Cannot have an equal sign in 【=】
        if(key.indexOf("=") !== -1) {
    
            throw new Error("Cookie I won't support it key Use the equal sign in 【=】, key:" + key)
        }
        let exdate = new Date() //  Acquisition time 
        exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) //  Days saved 
        //  String splicing cookie
        // eslint-disable-next-line camelcase
        window.document.cookie = key + '=' + value + ';path=/;expires=' + exdate.toGMTString()
    },

    get: function (key) {
    
        if (document.cookie.length > 0) {
     
            //  The format shown here needs to be cut. You can output it and have a look 
            var arr = document.cookie.split('; ')
            for (let i = 0; i < arr.length; i++) {
    
                let arr2 = arr[i].split('=') //  Cut again 
                //  Judge and find the corresponding value 
                if (arr2[0] === key) {
    
                    var value = arr2[1];
                    for (let j = 2; j < arr2.length; j++) {
    
                        value += '=' + arr2[j];
                    }
                    return value;
                }
            }
        }
    },

    remove: function (key) {
    
        set(key, '', -1);
    }
};
原网站

版权声明
本文为[Just a craftsman]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210649532773.html