Reputation: 967
I have a javascript cookie on my site and I've come across some code that identifies if the CookieConsent = true
cookie has been placed after a cookie banner is clicked to accept cookies.
I came across the code below that checks to see if the Cookie Consent does equal true, and by the looks of it, it is checking to see if there is any text after the CookieConsent=
part of the cookie string?
I have no idea how this is working though.
The bits that I do understand are:
But how does the .indexOf('CookieConsent=') == 0 }).length)
part of this code work.
Any explanation would be hugely appreciated.
if (document.cookie.split(';').filter(function(item) {
return item.trim().indexOf('CookieConsent=') == 0
}).length) {
// prevents cookie notice showing on next visit by adding a class to hide the cookie banner
cookieBanner.classList.add('hidden');
}
Upvotes: 0
Views: 1002
Reputation: 782166
The filter()
function returns an array of all the elements of the original array that match a condition. In this case, the original array is the one that results from splitting the document.cookie
at ;
delimiters.
item.trim().indexOf('CookieConsent=')
returns the position of the string of CookieConsent=
.
== 0
tests whether that position is 0
, so it's testing whether the string begins with CookieConsent=
.
Thus, the filter()
call returns an array of all the cookies that begin with CookieConsent=
.
.length
returns the length of this filtered array. It will be 0 if no such cookies were found, non-zero if there were any.
Any non-zero number is truthy, so the if
condition will succeed if a CookieConsent
cookie was found.
Upvotes: 1