Get cookies with javascript

I’m trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you’ve chosen. JavaScript code:

function cssLayout() < document.getElementById("css").href = this.value; >function setCookie() < var date = new Date("Februari 10, 2013"); var dateString = date.toGMTString(); var cookieString = "Css=document.getElementById("css").href" + dateString; document.cookie = cookieString; >function getCookie()
 
Select your css layout:

what i wonder is how to set cookie based on a choice. If i choose a specific css file, then i want that file to be saved and activated the next time i open the html file

@DrWooolie How about marking an answer correct so visitors to this question will find the best answer? The top answer clearly isn’t the best.

A concise but fully featured modern approach to get/set cookies over at the duplicate question: stackoverflow.com/a/48706852/87520

4 Answers 4

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) < var expires = ""; if (days) < var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); >document.cookie = name + "=" + (value || "") + expires + "; path=/"; > function getCookie(name) < var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) < var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); >return null; > function eraseCookie(name) < document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; >

Now, calling functions

setCookie('ppkcookie','testcookie',7); var x = getCookie('ppkcookie'); if (x)

They updated the page today so everything in the page should be latest as of now.

Читайте также:  Php скрипт мой ip адрес

The eraseCookie function didn’t work for me (FireFox Developer Edition 66.0b4). Instead, I had to use the code from B T’s answer: document.cookie = name + ‘=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/’ .

Nice answer. While using semicolon(;) in cookie value I have got problem. So I refined some lines. Please update in your answer. From function setCookie(name,value,days) document.cookie = name + «=» + (encodeURIComponent(value) || «») + expires + «; path=/»; From function getCookie(name) if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length)); Use encodeURIComponent(), decodeURIComponent() in retutn statement;

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1 document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/' // sets the cookie cookie2 (cookie1 is *not* overwritten) document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/' // remove cookie2 document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/' 

The Mozilla reference even has a nice cookie library you can use.

It looks like IE8 and below do not support max-age , so expires is the safer choice. blogs.msdn.com/b/ieinternals/archive/2009/08/20/…

There’s also a domain param you can set on cookies which is useful if you want to use a cookie across different sub domains on your site.

Note that the MDN reference page mentions nothing about expires being deprecated/obsolete. That’s because it can, on occasion, serve a purpose not covered by max-age . The value of max-age must be a numerical value interpreted as an amount of seconds, while the expires value can be set to the special value Session which is not the same as max-age=0; .

Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.

Just use the setCookie and getCookie methods mentioned there.

So, the code will look something like:

   

I just checked our analytics, and 10% of our IE users still use IE8 or lower. So using ‘max-age’ is a pretty bad idea.

I’m sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.

This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:

var docCookies = < getItem: function (sKey) < return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; >, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) < if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) < return false; >var sExpires = ""; if (vEnd) < switch (vEnd.constructor) < case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; >> document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; >, removeItem: function (sKey, sPath, sDomain) < if (!sKey || !this.hasItem(sKey)) < return false; >document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : ""); return true; >, hasItem: function (sKey) < return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); >, keys: /* optional method: you can safely remove it! */ function () < var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nIdx = 0; nIdx < aKeys.length; nIdx++) < aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); >return aKeys; > >; 

Mozilla has some tests to prove this works in all cases.

There is an alternative snippet here:

Источник

JavaScript Cookies

In this tutorial you will learn how to create, read, update and delete a cookie in JavaScript.

A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user’s computer. They are typically used for keeping track of information such as user preferences that the site can retrieve to personalize the page when user visits the website next time.

Cookies are an old client-side storage mechanism that was originally designed for use by server-side scripting languages such as PHP, ASP, etc. However, cookies can also be created, accessed, and modified directly using JavaScript, but the process is little bit complicated and messy.

Tip: A cookie can be up to 4 KB, including its name and values, cookies that exceed this length are trimmed to fit. Also, each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request.

Warning: Don’t store sensitive data such as a password or credit card information in cookies since it could potentially be manipulated by the malicious user.

In JavaScript, you can create, read, and delete cookies with the document.cookie property. This property represents all the cookies associated with a document.

To create or store a new cookie, assign a name=value string to this property, like this:

A cookie value cannot contain semicolons, commas, or spaces. For this reason, you will need to use the JavaScript’s built-in function encodeURIComponent() to encode the values containing these characters before storing it in the cookie. Likewise, you’ll need to use the corresponding decodeURIComponent() function when you read the cookie value.

By default, the lifetime of a cookie is the current browser session, which means it is lost when the user exits the browser. For a cookie to persist beyond the current browser session, you will need to specify its lifetime (in seconds) with a max-age attribute. This attribute determine how long a cookie can be remain on the user’s system before it is deleted, e.g., following cookie will live for 30 days.

document.cookie = «firstName=Christopher; max-age red-box break»> document.cookie = «firstName=Christopher; expires=Thu, 31 Dec 2099 23:59:59 GMT»;

Here’s a function that sets a cookie with an optional max-age attribute. You can also use the same function to delete a cookie by passing the value 0 for daysToLive parameter.

Example

function setCookie(name, value, daysToLive) < // Encode value in order to escape semicolons, commas, and whitespace var cookie = name + "=" + encodeURIComponent(value); if(typeof daysToLive === "number") < /* Sets the max-age attribute so that the cookie expires after the specified number of days */ cookie += "; max-age green-box break">document.cookie = "firstName=Christopher; path=/";

Further, you can use the domain attribute if you want a cookie to be available across subdomains. By default, cookies are available only to the pages in the domain they were set in.

If a cookie created by a page on blog.example.com sets its path attribute to / and its domain attribute to example.com, that cookie is also available to all web pages on backend.example.com, portal.example.com. However, you cannot share cookies outside of a domain.

document.cookie = "firstName=Christopher; path=/; domain=example.com";

There is also a boolean attribute named secure. If this attribute is specified, the cookie will be only be transmitted over a secure (i.e. encrypted) connection such as HTTPS.

document.cookie = "firstName=Christopher; path=/; domain=example.com; secure";

Reading a cookie is a slightly more complex because the document.cookie property simply returns a string containing a semicolon and a space separated list of all cookies (i.e. name=value pairs, for example, firstName=John; lastName=Doe;). This string doesn't contain the attributes such as expires, path, domain, etc. that may have been set for the cookie.

In order to get the individual cookie from this list, you need to make use of split() method to break it into individual name=value pairs, and search for the specific name, as shown below:

Example

Try this code »
function getCookie(name) < // Split cookie string and get all individual name=value pairs in an array var cookieArr = document.cookie.split(";"); // Loop through the array elements for(var i = 0; i < cookieArr.length; i++) < var cookiePair = cookieArr[i].split(" example break"> 

Example

Try this code »
function checkCookie() < // Get cookie using our custom function var firstName = getCookie("firstName"); if(firstName != "") < alert("Welcome again, " + firstName); >else < firstName = prompt("Please enter your first name:"); if(firstName != "" && firstName != null) < // Set cookie using our custom function setCookie("firstName", firstName, 30); >> >

The only way to update or modify a cookie is to create another cookie with the same name and path as an existing one. Creating a cookie with the same name but with a different path then that of an existing one will add an additional cookie. Here's an example:

Example

// Creating a cookie document.cookie = "firstName=Christopher; path=/; max-age=" + 30*24*60*60; // Updating the cookie document.cookie = "firstName=Alexander; path=/; max-age example break"> 

Example

Try this code »
// Deleting a cookie document.cookie = "firstName=; max-age=0"; // Specifying path and domain while deleting cookie document.cookie = "firstName=; path=/; domain=example.com; max-age=0";

However, to delete a cookie using the expires attribute, simply set its value (i.e. the expiration date) to a date that has already passed, as demonstrated below.

Источник

Оцените статью