We have looked a cookies in the browser earlier. With HTML5
we got an extension to the phenomenon of the browser gaining
a minimal access to the file system of the user.
This is called web storage. The formal reference is to the
https://www.w3.org/TR/webstorage/.
For daily practical use you may prefer to
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API.
From the latter of the two focus on the two properties of the
window object: localStorage, and
sessionStorage.
index.js
'use strict';
export const $ = function (foo) { return document.getElementById(foo); }
export const areCookiesEnabled = function() {
let now = new Date();
document.cookie = `_testCookie=${now};sameSite=Lax;path=/`;
console.log(now.toTimeString());
return document.cookie.indexOf(now) !== -1;
}
/*
* Alternative from https://stackoverflow.com/questions/16427636/check-if-localstorage-is-available
*/
export function isLocalStorageEnabled(){
let foo = 'bar';
try {
localStorage.setItem(foo, foo);
localStorage.removeItem(foo);
return true;
} catch(e) {
return false;
}
}
write.html
<!doctype html>
<html>
<head>
<meta charset='utf-8'/>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta name='generator' content='Geany 1.37'/>
<title>Write</title>
</head>
<body>
<script type='module'>
import {isLocalStorageEnabled} from './index.js';
if (isLocalStorageEnabled) {
localStorage.removeItem('foo');
let bar = {
name: "Niels",
position: "Prof"
};
bar.age = 75;
let foo = JSON.stringify(bar);
localStorage.setItem('foo', foo);
} else {
console.log('You must allow local storage in your browser');
}
</script>
<p><a href='.'>home</a></p>
</body>
</html>
read.html
<!doctype html>
<html>
<head>
<meta charset='utf-8'/>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta name='generator' content='Geany 1.37'/>
<title>Read</title>
</head>
<body>
<script type='module'>
import {isLocalStorageEnabled} from './index.js';
if (isLocalStorageEnabled) {
let foo = localStorage.getItem('foo');
foo = JSON.parse(foo);
console.log(`foo.name = ${foo.name}\nfoo.position = ${foo.position}\nfoo.age = ${foo.age}`);
} else {
console.log('You must allow local storage in your browser');
}
</script>
<p><a href='.'>home</a></p>
</body>
</html>