Storing cookies in javascript


Storing cookies in javascript

Cookies transport data between the web browser and the web server automatically, allowing CGI scripts to read and write cookie values saved on the client. JavaScript may also use the cookie attribute of the Document object to modify cookies.

The secure portion, a boolean value, is the last part of the cookie string, and false is the default settings. Suppose the cookie is designated secure (i.e., the secure value is true). In that case, it will be transmitted to the web server, which will attempt to retrieve it over a secure communication channel. This is true for servers that have SSL (Secure Sockets Layer) capabilities.

Example:

The following web content provides name, value, expires, and path portions to the function 'CookieSet.' The secure and domain sections aren't required in this case. Expires and path parts have empty values, and there is a check for expires and path parts. If expires receives an empty value, the expiration date will be set to If path receives an empty value, the path will be the current directory and subdirectories nine months from the current date. The toUTCString function turns a date into a string using the universal time standard.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>JavaScript creating cookies - example1</title> <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'}); var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:''; j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-NMDJMFC');</script> <!-- End Google Tag Manager --> </head> <body style="background-color:#EAEAE8"> <body> <h1 style="color:red">JavaScript creating cookies - example1</h1> <hr /> <script type="text/javascript"> //This is done to make the following JavaScript code compatible to XHTML. <![CDATA[ function CookieSet (cName, cValue, cPath, cExpires) { cvalue = encodeURIComponent(cValue); if (cExpires == "") { var cdate = new Date(); cdate.setMonth(cdate.getMonth() + 9); cExpires = cdate.toUTCString(); } if (cPath != "") { cPath = ";Path=" + cPath; } document.cookie = cName + "=" + cValue +"expires=" + cExpires + cPath; } CookieSet("Name","George ","",""); alert(document.cookie) //]]> </script> </body> </html>