Share a class for adding, deleting, and modifying cookies in javascript

Source: Internet
Author: User

I have been unemployed at school for one and a half months. I haven't found an internship yet. It's a tragedy and it hurts. cookie. js has changed to the pure javascript version. For future projects, I only need to add a function to get all the cookie key values on the page.

The function is assembled by analyzing the document. cookie string.

Review the operations on cookies in javascript:

You can use document. cookie = "userId = 111"; to add a cookie.

Full Version: document. cookie = "userId = 111; domain = .google.com; path = \; secure = secure; expire =" + date. toGMTString ();

You can set the cookie expiration time, domain name, and path.

You only need to delete it before setting the expire time to the current time.

Now I am modifying the javascript. cookie. js class

View Code

/*cookie helper classeasy to write,get,delete */var myCookie={    get:function(name){        if(typeof name != "undefined")        {            //if name given call the get value function            return myCookie_get(name);        }else{            //if name is not given,i want get all the cookie item            return myCookie_getAll();        }    },    add:function(name,value,options){        //write the cookie        myCookie_add(name,value,options);    },    delete:function(name){        //delete the cookie        myCookie_add(name,null);    }}String.prototype.Trim = function(){    return this.replace(/^\s+/g,"").replace(/\s+$/g,"");}/*cookie write function@name:the cookie name not null@value:the cookie value null==delete the cookie@option:{"expires":expire time;"path":/;"domain":localhost;"secure":secure} */function myCookie_add(name,value,options){    if (typeof value != 'undefined') { // name and value given, set cookie        options = options || {};        if (value === null) {            value = '';            options.expires = -1;        }        var expires = '';        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {            var date;            if (typeof options.expires == 'number') {                date = new Date();                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));            } else {                date = options.expires;            }            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE        }        var path = options.path ? '; path=' + options.path : '';        var domain = options.domain ? '; domain=' + options.domain : '';        var secure = options.secure ? '; secure' : '';        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');    }}/*get the name cookie@name:the cookie's name */function myCookie_get(name){    var cookieValue = null;    if (document.cookie && document.cookie != '') {        var cookies = document.cookie.split(';');        for (var i = 0; i < cookies.length; i++) {            var cookie = cookies[i].Trim();            // Does this cookie string begin with the name we want?            if (cookie.substring(0, name.length + 1) == (name + '=')) {                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));                break;            }        }    }    return cookieValue;}/*get all the cookie return as a json */function myCookie_getAll(){    var cookieArray = new Array();    var str="";    var temp;    if (document.cookie && document.cookie != '') {        var cookies = document.cookie.split(';');        for (var i = 0; i < cookies.length; i++) {            var cookie = cookies[i].Trim();            temp=cookie.split('=');            //take the            cookieArray.push("{\"name\":\""+decodeURIComponent(temp[0])+"\",\"value\":\""+decodeURIComponent(temp[1])+"\"}");        }        str=cookieArray.join(",");    }    str="["+str+"]";    return eval('('+str+')');}

The call is also quite simple.

View Code

MyCookie. add ("useraccount", "admin", {"expires": 5}); // add a cookie alert (myCookie. get ("useraccount"); // retrieve cookie cookies = myCookie. get (); // get all cookies for (var I = 0; I <cookies. length; I ++) {alert (cookies [I] ["name"] + ":" + cookies [I] ["value"]);} myCookie. delete ("useraccount"); // delete the cookie alert (myCookie. get ("useraccount "));

Hope you can provide guidance

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.