Read javascript advanced programming 17-Online Detection, cookie, sub-cookie

Source: Internet
Author: User
Tags set cookie

Read javascript advanced programming 17-Online Detection, cookie, sub-cookie
When developing offline applications, data is often stored locally while offline, and sent to the server when online. Html5 provides a method to check the onLine status: navigator. online and onLine/offline events. 1. the navigator. onLine attribute indicates whether the current network status is onLine. true indicates onLine, and false indicates offline. This attribute also changes when the network status changes. 2. online and offline events HTML5 provide these two events, which will be triggered when the network status changes. Online is triggered when the network changes from offline to online. offline is triggered when the network changes from online to offline. Copy the Code <p> You are currently: <span id = "status"> <script> document. write (navigator. onLine? "Online": "offline"); </script> </span> </p> <p> switch to offline status to see the effect </p> <script> EventUtil. addHandler (window, "online", function () {document. getElementById ("status "). innerHTML = "online" ;}); EventUtil. addHandler (window, "offline", function () {document. getElementById ("status "). innerHTML = "offline" ;}); </script> copy Code 2 and cookie 1. cookie composition: Name: the cookie name must be a URL-encoded string. Although it is case-insensitive, we recommend that you use it as case-sensitive. Value: the string value in the cookie, which must also be a URI-encoded string. Domain: indicates the domain in which the cookie is valid. Path: the directory in which the cookie takes effect. Expiration time: indicates the timestamp of the cookie expiration time, which is a date in GMT format. When this event is set to a value smaller than the current value, the cookie is deleted. Security ID: After this ID is specified, the cookie is sent to the server only when the SSL request is used for connection. The secure identifier is the only non-key-Value Pair in a cookie that contains only one secure word. 2. The cookie read/write deletion operation can use document. cookie in JavaScript to read the cookies under the current domain name. It is a string consisting of key-value pairs separated by semicolons. Similar to name = aa; age = 15; note that all key-value pairs are encoded by encodeURIComponent () and must be decoded during use. When a value is assigned to document. cookie, a new cookie is appended instead of directly overwriting the existing cookie. For example: document. cookie = "a = 1"; // after execution, a new cookie is displayed. Common Methods for deleting and reading cookies in Image: copy the code var CookieUtil ={// read the cookie get: function (name) based on the key {// note the key encoding var cookieName = encodeURIComponent (name) + "=", cookieStart = document. cookie. indexOf (cookieName), cookieValue = null, cookieEnd; // find the cookie key if (cookieStart>-1) {// The first semicolon position after the key cookieEnd = document. cookie. indexOf (";", cookieStart); if (cookieEnd =-1) {cookieEnd = document. cookie. length;} // decodes co from the cookie value OkieValue = decodeURIComponent (document. cookie. substring (cookieStart + cookieName. length, cookieEnd);} return cookieValue;}, // set cookie set: function (name, value, expires, path, domain, secure) {var cookieText = encodeURIComponent (name) + "=" + encodeURIComponent (value); // expiration time. In GMT format, if (expires instanceof Date) {cookieText + = "; expires =" + expires. toGMTString ();} if (path) {cookieText + = "; Path =" + path;} if (domain) {cookieText + = "; domain =" + domain;} if (secure) {cookieText + = "; secure ";} document. cookie = cookieText;}, // Delete the cookie, keep the same key, domain, path, and security options, and set the expiration time to unset: function (name, path, domain, secure) {this. set (name, "", new Date (0), path, domain, secure) ;}; copy the code instance: copy the Code <p id = "know"> tip area 1 <a href = "javascript: void (0) "target =" _ self "id =" btn-know "> no longer prompts </a> </ P> <input type = "button" value = "Clear cookie" id = "delete-btn"/> <script type = "text/javascript"> var cookiekey = "OK "; eventUtil. addHandler (window, "load", function () {var know1 = CookieUtil. get (cookiekey); if (know1) {document. getElementById ("know "). style. display = "none";} EventUtil. addHandler (document. getElementById ("delete-btn"), "click", function () {CookieUtil. unset (cookiekey) ;})}; EventUtil. addHa Ndler (document. getElementById ("btn-know"), "click", function () {CookieUtil. set (cookiekey, "1"); document. getElementById ("know "). style. display = "none" ;}); </script> copy code 3. A sub-cookie sometimes requires that the site record multiple cookies. For example, if a bubble prompt is displayed in multiple functional areas, click "No prompt" to cancel the reminder. At this time, a simple cookie must be recorded in each region. Because the number of browser cookies is limited, you can use the subcookie method to reduce the number of cookies. Multiple key-value pairs can be stored in a cookie value in a format similar to a query string, so that each key-Value Pair does not occupy one cookie. Example of the sub-cookie value: iknow = know0 = 1 & know1 = 1 ① get all the sub-cookies and put them in an object to return the result. The object's attribute name is the sub-cookie name, the property value of the object is the value of the sub-cookie. Copy the code getAll: function (name) {var cookieName = encodeURIComponent (name) + "=", cookieStart = document. cookie. indexOf (cookieName), cookieValue = null, cookieEnd, subCookies, I, parts, result ={}; if (cookieStart>-1) {cookieEnd = document. cookie. indexOf (";", cookieStart) if (cookieEnd =-1) {cookieEnd = document. cookie. length;} // retrieves the cookie string value cookieValue = document. cookie. substring (cookieStart + CookieName. length, cookieEnd); if (cookieValue. length> 0) {// use & to separate cookie values into arrays subCookies = cookieValue. split ("&"); for (I = 0, len = subCookies. length; I <len; I ++) {// equals sign to separate the key-value pairs parts = subCookies [I]. split ("="); // assign the decoded part-time pair as the property name and attribute value to the object result [decodeURIComponent (parts [0])] = decodeURIComponent (parts [1]);} return result ;}} return null;} copy the code ② get () to obtain a single sub-cookie. Copy the code get: function (name, subName) {// obtain all sub-Cookies var subCookies = this. getAll (name); if (subCookies) {// obtain a single sub-cookie from the attribute return subCookies [subName];} else {return null ;}} copy code ③ setAll: function (name, subcookies, expires, path, domain, secure) {var cookieText = encodeURIComponent (name) + "= ", subcookieParts = new Array (), subName; // traverses the attributes of the subcookie object for (subName in subcookies ){ // Check the property name if (subName. length> 0 & subcookies. hasOwnProperty (subName) {// After the attribute name and attribute value are encoded = connected as a string, and placed in the array subcookieParts. push (encodeURIComponent (subName) + "=" + encodeURIComponent (subcookies [subName]) ;}} if (subcookieParts. length> 0) {// use & connect to the cookie string cookieText + = subcookieParts. join ("&"); if (expires instanceof Date) {cookieText + = "; expires =" + expires. toGMTString ();} if (path) {cookieText + = "; Path =" + path;} if (domain) {cookieText + = "; domain =" + domain;} if (secure) {cookieText + = "; secure ";}} else {cookieText + ="; expires = "+ (new Date (0 )). toGMTString ();} // sets the entire cookie document. cookie = cookieText;} ④ set a single sub-cookie set: function (name, subName, value, expires, path, domain, secure) {// obtain the current cookie object var subcookies = this. getAll (name) | |{}; // replace subcookies with attributes corresponding to a single cookie [SubName] = value; // reset cookie this. setAll (name, subcookies, expires, path, domain, secure);} copy code ⑤ delete a cookie and set the expiration time to the expiration date. UnsetAll: function (name, path, domain, secure) {this. setAll (name, null, new Date (0), path, domain, secure);} to delete a single sub-cookie, you must first obtain all sub-cookie objects, delete the attributes corresponding to the sub-cookie, and then reset the sub-cookie object. Copy the code unset: function (name, subName, path, domain, secure) {// obtain the current cookie object var subcookies = this. getAll (name); if (subcookies) {// delete the subcookie attribute delete subcookies [subName]; // reset the cookie this. setAll (name, subcookies, null, path, domain, secure) ;}} copy Code 6 call instance: Multiple bubble prompt areas, the "no longer prompting" function cookie is recorded in the same cookie. Copy the Code <p id = "know0"> friendly tip area 1 <a href = "javascript: void (0) "target =" _ self "id =" btn-know0 "> no longer prompts </a> </p> <p id =" know1 "> friendly tip area 2 <a href =" javascript: void (0) "target =" _ self "id =" btn-know1 "> no longer prompts </a> </p> <input type =" button "value =" Clear cookie "id =" delete -btn "/> <script type =" text/javascript "> var cookiekey = 'iknow ', key0 = 'know0', key1 = 'know1'; EventUtil. addHandler (window, 'load', function () {var know0 = SubCookieUtil. get (cookiekey, key0); if (know0) {document. getElementById ('know0 '). style. display = 'none';} var know1 = SubCookieUtil. get (cookiekey, key1); if (know1) {document. getElementById ('know1 '). style. display = 'none';} EventUtil. addHandler (document. getElementById ('delete-btn '), 'click', function () {SubCookieUtil. unset (cookiekey, key0); SubCookieUtil. unset (cookiekey, key1) ;}) EventUtil. addHandler (document. getElementById ('btn-know0'), 'click', function () {SubCookieUtil. set (cookiekey, key0, 1); document. getElementById ('know0 '). style. display = 'none';}); EventUtil. addHandler (document. getElementById ('btn-know1'), 'click', function () {SubCookieUtil. set (cookiekey, key1, 1); document. getElementById ('know1 '). style. display = 'none';}) ;}); </script>

Related Article

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.