- acceptance will remove the panel from the website by checking on each load if the cookies_enabled property has the value 1
For this operation we will use the Web Storage API and more exactly of it’s mechanisms called localstorage. One important thing to mention here is that localstorage never expires unless you define it so.
The syntax is pretty simple, it has a setItem() for adding, getItem() for retrieving data from the file, removeItem() to delete a specific key-value in a storage, clear() which clears all localstorages and also 1 additional method: key() that accepts a number as argument, returning the key by order.
The clear() method is not safe ! If you are running multiple projects on localhost, then you’ll wipe all of your values out in an instant. It’s better to use removeItem() to keep it safe, by individually removing storages of your choice.
Now, let’s start with the code and deconstruct it:
First step is to set up an expiry countdown in hours representing half a year (in this case). In the now variable we put the today’s date and in setupTime we try to retrieve expiration data from local storage.
So in simple terms, if from a certain date till today more then half a year passed(now – setupTime) then delete localstorage.
Of course we can use localStorage.removeItem(‘cookies_enabled’); to avoid deleting other local storages from same domain.
- we set again the value 1 to cookie_enabled and the setupTime with start date from where the countdown starts (half a year)