Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / JavaScript

Storage.getItem — leggere un valore di Web Storage

Storage.getItem(key) legge in modo sincrono il testo da localStorage o sessionStorage. Restituisce null se la chiave non esiste; una stringa vuota è un valore presente, non una voce mancante.

Versione: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Sintassi

storage.getItem(key)

Storage.getItem è un metodo di istanza di Storage, usato da localStorage e sessionStorage. Accetta una chiave testuale e restituisce il testo memorizzato oppure null se la voce non esiste. La lettura è sincrona e non rimuove la voce.

Distingui null, "" e "null". Verifica l’assenza con value === null, non con !value, che corrisponde anche a una stringa vuota. Numeri e oggetti memorizzati non recuperano automaticamente i rispettivi tipi.

Questa è una Web API definita dall’HTML Living Standard, non una funzionalità di una specifica edizione di ECMAScript. È ampiamente supportata dai browser moderni; la versione di Node del repository non dimostra il supporto nei browser. Il solo accesso a window.localStorage o window.sessionStorage può generare un SecurityError a causa di un’origine opaca o delle politiche del browser.

L’esempio distingue una stringa vuota, la stringa "42" e una voce mancante. Sceglie una chiave inutilizzata e rimuove la voce temporanea per verificare che la lettura restituisca null. Il blocco finally ripete la rimozione per eliminare la voce anche in caso di errore, senza svuotare l’intera area di archiviazione.

Esempi

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Storage.getItem: empty and missing values</title>
</head>
<body>
<h1>Reading a storage value</h1>
<p id="source"></p>
<script>
  function readValues(storage) {
    let key = 'cktis:getItem';
    while (storage.getItem(key) !== null) key += ':';

    try {
      storage.setItem(key, '');
      const empty = storage.getItem(key);
      storage.setItem(key, '42');
      const text = storage.getItem(key);
      storage.removeItem(key);
      return [JSON.stringify(empty), JSON.stringify(text), storage.getItem(key) === null];
    } finally {
      storage.removeItem(key);
    }
  }

  let lines;
  let source = 'Using browser sessionStorage.';
  try {
    lines = readValues(window.sessionStorage);
  } catch (error) {
    if (error.name !== 'SecurityError' && error.name !== 'QuotaExceededError') throw error;
    source = error.name === 'QuotaExceededError'
      ? 'Could not write the demo value to sessionStorage. Existing entries may still be readable. Using an in-memory fixture, not Web Storage.'
      : 'Browser storage is unavailable. Using an in-memory fixture, not Web Storage.';
    const entries = new Map();
    lines = readValues({
      getItem(key) { return entries.has(key) ? entries.get(key) : null; },
      setItem(key, value) { entries.set(key, String(value)); },
      removeItem(key) { entries.delete(key); }
    });
  }
  document.getElementById('source').textContent = source;
  for (const line of lines) console.log(line);
</script>
</body>
</html>

Risultato

""
"42"
true

Il codice mostrato e il risultato dichiarato sono stati verificati in un ambiente isolato con il metodo registrato nella prova di verifica di questa versione esatta.

Fonti