JBM-Computing

Cookie consent

JavaScript has the document.cookie property: read it to see all the cookies for the current page; set it to overwrite an existing or add a new cookie.

  • when setting a cookie you must specify the name and value and can optionally specify an expiry date (defaults to when the browser is closed) and a path (defaults to the current page)
  • reading a cookie returns a string with just the name and value for each cookie

The current document.cookie :

 

Below is a self-contained script that will display a banner and set a “consent” cookie.

 

<script src="cookies.js" defer></script>
load the cookies.js script
defer downloads the script in parallel to parsing the page and executes it after the page has finished parsing

 

.c-div {position:fixed; top:0; right:0; bottom:0; left:0; background-color:RGBA(255,255,255,0.75); backdrop-filter:blur(2px); z-index:9999}
whole page div: looks like a layer of frosted glass on top of the web page
.c-content {position:absolute; bottom:10%; left:50%; transform:translate(-50%,0); width:200px; padding:10px; text-align:center; background-color:#FFFFFF; box-shadow:1px 1px 5px RGBA(0,0,0,0.5)}
the cookie message div: 10% from the bottom, centered with a white background and drop-shadow
.c-OK {display:block; margin:10px auto 0; padding:8px 25%; color:#FFFFFF; background-color:#808080}
the OK button: centered with a grey background

These styles apply to elements created by the JavaScript

Obviously you can go wild with the style - this example has been kept relatively simple

 

(function(){
anonymous (no name) function (the parentheses wrapping the function make it an expression rather than declaration) - defined and executed immediately (contained functions, variables, etc are removed from the current scope as soon as it finishes)
const cookieName = '_myCookieConsent_'
const path = '/'
const cookieValue = 'OK'
const expiryDays = 365
function setCookie(_n, _v, _d){
set cookie with _n name, _v value & expiry date _d days in the future
const _e = new Date(Date.now() + (_d * 24 * 60 * 60 * 1000)).toUTCString()
create _e expiry date, _d days from now (Date.now() returns number of milliseconds since 00:00 on 1 January 1970)
document.cookie = _n + '=' + _v + '; expires=' + _e + '; path=' + path
write the cookie (this would overwrite a cookie with the same name in the same path)
}
function dismissBanner(){
when clicking the 'OK' button
setCookie(cookieName, cookieValue, expiryDays)
set the '_myCookieConsent_' cookie
document.querySelector('.c-div').remove()
delete the div with class="c-div"(which removes the whole cookie banner overlay)
}
function getCookieValue(_n){
get the value of the cookie named _n
const nameEQ = _n + '='
const ca = document.cookie.split(';')
get the document.cookie and split it into an array of name=value elements
for (let i=0; i<ca.length; i++){
for each array element
let c = ca[i]
c = current array element
while (c.charAt(0) === ' ') c = c.substring(1, c.length)
while the 1st character of the string is a space, delete it
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length)
if the beginning of the string matches "_n=", return the cookie value
}
return null
if there’s no cookie or the _n cookie isn’t there, return null
}
if (getCookieValue(cookieName) !== cookieValue){
if our cookie “_myCookieConsent_” does not = “OK”, create the html for the cookie banner
const cDiv = document.createElement('div')
create a div element
cDiv.classList.add('c-div')
give it the class "c-div"
document.body.append(cDiv)
add it just before the page’s </body> tag
const cContent = document.createElement('div')
create a div element
cContent.classList.add('c-content')
give it the class "c-content"
cDiv.append(cContent)
add it to the end of the above div
cContent.append('Your message about cookies goes here.')
add in your cookie message text
const cButton = document.createElement('button')
create a button element
cButton.classList.add('c-OK')
give it the class "c-OK"
cContent.append(cButton)
add it to the end of the content div
cButton.textContent = 'OK'
text for the button
cButton.addEventListener('click', dismissBanner)
click the button to dismiss the banner (set the cookie and delete the overlay)
}
})()
this final pair of parentheses invokes the function (and would pass it arguments if there were any)

This script will create the html for a cookie banner, but only if the consent cookie is not set.

Again, this example has been kept relatively simple - you can keep adding elements for a more involved cookie banner

 

Setting a cookie with an expiry date/time in the past will delete it.

Use this function for testing: it will delete just the _myCookieConsent_ cookie which should cause the banner to reappear:

function delMyCookieTest(){
const _day = new Date(Date.now() - 864000000).toUTCString()
create _day expiry date of this time yesterday (864,000,000 is the number of milliseconds in 1 day)
document.cookie = '_myCookieConsent_=""; expires=' + _day + '; path=/'
overwriting the cookie with a negative expiry date deletes it
top.location.reload()
reload the page to display the cookie banner (as there’s no cookie)
}

 

Copy the sections of script from above (without the notes) into this html skeleton for a working example cookie consent page:

<html>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
html {padding:20px 5%; font-family:sans-serif; background-color:#888}
body {height:115%; padding:20px; background-color:#FFF}
/* copy CSS here */
</style>
<body>
<h1>Cookie Consent Test</h1>
<p>Body text.</p>
<p>Click this button to delete your _myCookieConsent_ cookie for testing:<br><br>
<button onClick="delMyCookieTest()">delete cookie</button></p>
<script>
// copy JavaScript here
// copy delMyCookieTest JavaScript function here
</script>
</body>
</html>

You can also copy the JavaScript into an external file and replace the <script> section with the html from the top of this page.

Links

JBM-Computing

part of J E Mynott Limited

web: www.Mynott.uk

site map / contentswebsite privacy
glossarycontact me
©2000-2025 JBM-Computing
Facebook Twitter YouTube print