CKTIS / JavaScript
Pohrana preglednika
Pohrana preglednika obuhvaća mehanizme okruženja preglednika za čuvanje podataka na strani klijenta. Saznajte razliku između localStorage i sessionStorage te gdje je granica između jezika ECMAScript i web API-ja.
Verzija: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Sintaksa
localStorage.setItem(key, value);
localStorage.getItem(key);
localStorage.removeItem(key);Pohrana preglednika (browser storage) mogućnost je okruženja, a ne sintaksa ECMAScripta. Specifikacija ECMAScripta opisuje jezik i njegovu interakciju s host okruženjem; ne definira localStorage ni sessionStorage. To što je Node 24 prisutan u repozitoriju ne dokazuje da su ta sučelja dostupna u ciljnom pregledniku.
localStorage čuva parove ključ-vrijednost između sesija, dok je sessionStorage vezan uz sesiju stranice u određenoj kartici. Oba su sučelja sinkrona i pohranjuju nizove znakova. Ako ključ ne postoji, getItem(key) vraća null. Objekti se mogu pohraniti pomoću JSON.stringify i pročitati pomoću JSON.parse.
Pristup ovisi o podrijetlu stranice i pravilima preglednika. Podaci se mogu ukloniti, a pristup ili zapisivanje mogu izazvati iznimku. Nemojte ovu pohranu smatrati jedinom kopijom podataka ni mjestom za tajne. Odjeljak Web Storage HTML standarda skupine WHATWG definira localStorage i sessionStorage te njihove metode. Nije izvor podataka o kompatibilnosti s preglednicima i ne jamči da su ta sučelja dostupna u ciljnom pregledniku.
Primjeri
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Browser storage example</title>
</head>
<body>
<p>localStorage can persist across visits. sessionStorage is scoped to the page session in a tab. Both are browser APIs, not part of ECMAScript.</p>
<ul aria-label="Storage check results">
<li id="localStorage"></li>
<li id="sessionStorage"></li>
</ul>
<script>
const fixture = JSON.stringify({ theme: 'dark' });
function checkStorage(name) {
const result = document.getElementById(name);
try {
const store = window[name];
// A fresh temporary key avoids reusing application keys. This sequence is not atomic:
// another same-origin tab can change localStorage between calls.
const key = `cktis:storage:example:${crypto.getRandomValues(new Uint32Array(4)).join('-')}`;
if (store.getItem(key) !== null) {
throw new Error('Temporary storage key already exists');
}
store.setItem(key, fixture);
let saved;
try {
saved = store.getItem(key);
} finally {
store.removeItem(key);
}
if (saved !== fixture || store.getItem(key) !== null) {
throw new Error('Round trip or cleanup failed');
}
result.textContent = `${name}: read back theme=${JSON.parse(saved).theme}; temporary key removed.`;
} catch (error) {
if (!(error instanceof DOMException) || !['SecurityError', 'QuotaExceededError'].includes(error.name)) {
throw error;
}
result.textContent = `${name}: temporary write unavailable (${error.name}).`;
}
console.log(result.textContent);
}
checkStorage('localStorage');
checkStorage('sessionStorage');
</script>
</body>
</html>Rezultat
A successful check reports that it read back theme=dark and removed the temporary key. If the check catches a DOMException named SecurityError or QuotaExceededError, it reports that the temporary write is unavailable and includes the error name. Other errors, including a temporary-key collision or a detected round-trip or cleanup failure, are rethrown without a report for that storage area. If the localStorage check rethrows, the sessionStorage check does not run.
Prikazani kôd i navedeni rezultat provjereni su u izoliranom okruženju metodom zabilježenom u dokazu provjere za ovu točnu verziju.