|
<!DOCTYPE html> |
|
<html lang="en"> |
|
|
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
<meta http-equiv="X-UA-Compatible" content="ie=edge"> |
|
<title>Cookies</title> |
|
<style> |
|
html { |
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; |
|
font-size: 20px; |
|
line-height: 1.7; |
|
} |
|
|
|
body { |
|
min-height: 100vh; |
|
display: flex; |
|
flex-direction: column; |
|
} |
|
|
|
#output { |
|
padding: 2rem; |
|
border: 1px solid #333; |
|
font-size: 2rem; |
|
margin: 1rem; |
|
} |
|
|
|
button { |
|
font-size: 2rem; |
|
margin: 1rem; |
|
} |
|
</style> |
|
</head> |
|
|
|
<body> |
|
<div id="output"></div> |
|
|
|
<button id="btnAdd">Add a cookie</button> |
|
<button id="btnDel">Remove a cookie</button> |
|
<button id="btnFind">Check for cookie</button> |
|
|
|
<script> |
|
document.addEventListener('DOMContentLoaded', () => { |
|
|
|
document.body.addEventListener('click', (ev) => { |
|
//display the current cookie and display it in the output div |
|
if (document.cookie) { |
|
document.getElementById('output').textContent = document.cookie; |
|
//this will output all the key=value pairs |
|
} else { |
|
document.getElementById('output').textContent = 'No cookies currently'; |
|
} |
|
console.log(document.cookie.split(';')); |
|
}); |
|
|
|
document.getElementById('btnAdd').addEventListener('click', (ev) => { |
|
//set a cookie |
|
let key = 'score'; |
|
let value = encodeURIComponent('8745683465'); |
|
let thirty = 60 * 60 * 24 * 30; |
|
document.cookie = `${key}=${value};path=/;max-age=${thirty};`; // one cookie at a time |
|
// theme=gold; score=102923873; trackingid=AB3453453DF; |
|
/** |
|
;path= absolute path. current path by default. |
|
;domain=sub.example.com current domain by default. |
|
;max-age= seconds 60*60*24*30 30 days |
|
;expires= UTC date. end of current session by default |
|
;secure=true |
|
;same-site=Strict | Lax |
|
**/ |
|
}); |
|
|
|
document.getElementById('btnDel').addEventListener('click', (ev) => { |
|
//delete a cookie |
|
let key = 'theme'; |
|
document.cookie = `${key}=;path=/;expires=Thu, 01 Jan 1970T00:00:00Z;`; |
|
}); |
|
|
|
document.getElementById('btnFind').addEventListener('click', (ev) => { |
|
//find if a cookie exist |
|
let key = 'score'; |
|
let val = ''; |
|
if (document.cookie.split(';').filter(item => item.trim().startsWith(`${key}=`)) |
|
.length) { |
|
//cookie that starts with key= exists |
|
document.getElementById('output').textContent = `${key} key is found`; |
|
} else { |
|
document.getElementById('output').textContent = `${key} key is NOT found`; |
|
} |
|
ev.stopPropagation(); |
|
}); |
|
}); |
|
</script> |
|
</body> |
|
|
|
</html> |