Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a javascript cookie by name

I have set a cookie using

document.cookie =      'MYBIGCOOKIE=' + value +      '; expires=' + now.toGMTString() +      '; path=/'; 

Now there are between 5 and 10 cookies set on this site, is there a way to check the value ofthis cookie by name.

if (document.cookie.MYBIGCOOKIE == '1') {     alert('it is 1') } 
like image 879
Jimbo Avatar asked Feb 28 '11 13:02

Jimbo


People also ask

How do I get a cookie by name in JavaScript?

Here is a one liner to get a cookie value with a specific name without the need of any external lib: const value = ('; '+document. cookie). split(`; COOKIE_NAME=`).

How can I find the name of a cookie?

For Google Chrome go to View > Developer > Developer Tools or CMD + ALT + I on Mac or F12 on Windows. ‍Now open the Application tab and check the cookies for each domain. Usually the cookies have names that resemble the name of the service they are being used by.


2 Answers

Use the RegExp constructor and multiple replacements to clarify the syntax:

function getCook(cookiename)    {   // Get name followed by anything except a semicolon   var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie);   // Return everything after the equal sign, or an empty string if the cookie name not found   return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");   }  //Sample usage var cookieValue = getCook('MYBIGCOOKIE'); 
like image 145
Paul Sweatte Avatar answered Oct 04 '22 05:10

Paul Sweatte


Unfortunately, Javascript's cookie syntax is nowhere near as nice as that. In fact, in my opinion, it's one of the worst designed parts.

When you try to read document.cookie, you get a string containing all the cookies set. You have to parse the string, separating by the semicolon ; character. Rather than writing this yourself, there are plenty of versions available on the web. My favourite is the one at quirksmode.org. This gives you createCookie, readCookie and deleteCookie functions.

like image 44
lonesomeday Avatar answered Oct 04 '22 03:10

lonesomeday