Using localStorage and sessionStorage
When you want to store data on the user's browser, HTML provides two important storage APIs: localStorage and sessionStorage. Both allow you to save key-value pairs as strings, but they differ in how long the data persists and when it is available.
localStorage saves data with no expiration time. This means that if you store something in localStorage, it will still be there even after the user closes and reopens the browser, or restarts their computer. This is useful for things like saving user preferences, themes, or login states that you want to remember across sessions.
sessionStorage, on the other hand, only keeps data for the duration of the page session. As soon as the user closes the browser tab or window, the data is cleared. sessionStorage is best used for temporary data that is only relevant while the user is on a specific page or during a single visit, such as wizard progress or temporary form data.
Both storage types are easy to use. You set an item with setItem(key, value) and get it back with getItem(key). Remember, all data is stored as strings, so you may need to use JSON.stringify and JSON.parse for objects or arrays.
index.html
script.js
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Can you give examples of when to use localStorage vs sessionStorage?
How do I store and retrieve objects using these APIs?
Are there any security concerns with using localStorage or sessionStorage?
Fantastisk!
Completion rate forbedret til 7.14
Using localStorage and sessionStorage
Stryg for at vise menuen
When you want to store data on the user's browser, HTML provides two important storage APIs: localStorage and sessionStorage. Both allow you to save key-value pairs as strings, but they differ in how long the data persists and when it is available.
localStorage saves data with no expiration time. This means that if you store something in localStorage, it will still be there even after the user closes and reopens the browser, or restarts their computer. This is useful for things like saving user preferences, themes, or login states that you want to remember across sessions.
sessionStorage, on the other hand, only keeps data for the duration of the page session. As soon as the user closes the browser tab or window, the data is cleared. sessionStorage is best used for temporary data that is only relevant while the user is on a specific page or during a single visit, such as wizard progress or temporary form data.
Both storage types are easy to use. You set an item with setItem(key, value) and get it back with getItem(key). Remember, all data is stored as strings, so you may need to use JSON.stringify and JSON.parse for objects or arrays.
index.html
script.js
Tak for dine kommentarer!