Get cookie by name

前端 未结 30 1380
野的像风
野的像风 2020-11-22 03:58

I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:39

    I wrote something that might be easy to use, If anyone has some things to add, feel free to do so.

    function getcookie(name = '') {
        let cookies = document.cookie;
        let cookiestore = {};
        
        cookies = cookies.split(";");
        
        if (cookies[0] == "" && cookies[0][0] == undefined) {
            return undefined;
        }
        
        cookies.forEach(function(cookie) {
            cookie = cookie.split(/=(.+)/);
            if (cookie[0].substr(0, 1) == ' ') {
                cookie[0] = cookie[0].substr(1);
            }
            cookiestore[cookie[0]] = cookie[1];
        });
        
        return (name !== '' ? cookiestore[name] : cookiestore);
    }
    

    Usage

    getcookie() - returns an object with all cookies on the web page.

    getcookie('myCookie') - returns the value of the cookie myCookie from the cookie object, otherwise returns undefined if the cookie is empty or not set.


    Example

    // Have some cookies :-)
    document.cookie = "myCookies=delicious";
    document.cookie = "myComputer=good";
    document.cookie = "myBrowser=RAM hungry";
    
    // Read them
    console.log( "My cookies are " + getcookie('myCookie') );
    // Outputs: My cookies are delicious
    
    console.log( "My computer is " + getcookie('myComputer') );
    // Outputs: My computer is good
    
    console.log( "My browser is " + getcookie('myBrowser') );
    // Outputs: My browser is RAM hungry
    
    console.log( getcookie() );
    // Outputs: {myCookie: "delicious", myComputer: "good", myBrowser: "RAM hungry"}
    
    // (does cookie exist?)
    if (getcookie('hidden_cookie')) {
        console.log('Hidden cookie was found!');
    } else {
        console.log('Still no cookie :-(');
    }
    
    // (do any cookies exist?)
    if (getcookie()) {
        console.log("You've got cookies to eat!");
    } else {
        console.log('No cookies for today :-(');
    }
    

提交回复
热议问题