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') }
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=`).
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.
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With