Web developers inevitably need to process cookies. In the past, the process of processing cookies using javascript was cumbersome and error-prone. Therefore, some javascript code or jQuery class libraries that are ready-made to process cookies are often used, jQuery is good to use, but it is not very cost-effective to load such a large file just to process cookies. Today, we will introduce cookie. js, a javascript class library that helps you simplify cookie operations. It is not dependent on any third-party class library and is very small and only 1.4kb. Hope you like it!
Why use cookie. js?
Processing cookies with the original javascript code is ugly. document. cookie is definitely one of the ugliest javascript Functions. Using cookie. js can effectively help you process cookie-related functions, and is more interesting.
Usage
Import Class Library:
<Script src = "cookie. min. js"> </script>
Set cookie:
Cookie. set ('key', 'value ');
Alternatively, you can set multiple cookies at the same time:
Cookie. set ({
Key1: 'value1 ',
Key2: 'value2'
});
Of course, cookie. js also supports many options. You can add options as follows:
Cookie. set ('key', 'value ',{
Expires: 7, // expires in one week
});
In the above Code, the cookie will expire one week later.
Get cookie
Cookie. get ('key ');
Obtain an array key as follows:
Cookie. get (['key1', 'key2']);
Return an object. The keys of this object will be the keys you passed in, and the corresponding value will be the value obtained by the cookie.
You can also set the default value through this method:
Cookie. get ('key', 'default value ');
If a value is retrieved, the default value is returned. Multiple keys are supported at the same time:
Cookie. get (['key1', 'key2'], 'default value ');
The two methods are the same. cookie () is the abbreviation of cookie. get:
Cookie. get ('key ');
// Same effect
Cookie ('key ');
Get all cookies
Var cookies = cookie. all ();
Get all saved cookies and return an object containing all cookies.
Delete cookie
Deletes all cookies, which can be one or more keys.
Cookie. remove ('key ');
Cookie. remove ('key1', 'key2 ');
Cookie. remove (['key1', 'key2']);
Clear cookie
Cookie. empty ()
Test whether the cookie is available
If (cookie. enabled ()){
// Do stuff with cookies
} Else {
// Display error message or use localStorage
}
The above method tests whether the current cookie is available. If it is unavailable, you may need to consider using the fallback method for processing.
Chain Operation
Cookie. empty (). set ('key', 'value'). set ('key2', 'value2'). remove ('key1 ');
Main parameters:
Option |
Option value |
Default Value |
Expires |
Used to set the number of days of expiration, which can be GMTStringformat or a date object |
Expired when the browser is closed |
Domain |
A string used to specify the Domain Name |
Current Domain Name |
Path |
Specify the cookie access path |
Current path |
Secure |
Whether to use secure link to access cookies |
False |
From GBin1.com