How to store temporary data in javascript
Modern web browsers support a number of ways for web sites to store data on the user's computer — with the
user's permission — then retrieve it when necessary. This lets you persist data for long-term storage, save sites or documents for offline use, retain user-specific settings for your site, and more. This article explains the very basics of how these work. Elsewhere in the MDN learning area we talked about the difference between static sites and
dynamic sites. Most major modern web sites are dynamic — they store data on the server using some kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting HTML to the client to
be displayed by the user's browser. Client-side storage works on similar principles, but has different uses. It consists of JavaScript APIs that allow you to store data on the client (i.e. on the user's machine) and then retrieve it when needed. This has many distinct uses, such as: Often client-side and server-side storage are used together. For example, you could download a batch of music files (perhaps used by a web game or music player application), store them
inside a client-side database, and play them as needed. The user would only have to download the music files once — on subsequent visits they would be retrieved from the database instead. Note: There are limits to the amount of data you can store using client-side storage APIs (possibly both per individual API and cumulatively); the exact limit varies depending on the browser and possibly based on user settings. See
Browser storage limits and eviction criteria for more information. The concept of client-side storage has been around for a long time. Since the early days of the web, sites have used cookies to store information to personalize user experience on websites. They're the earliest form of client-side storage commonly used on the web. These days, there are easier mechanisms available for storing client-side data, therefore we won't be teaching you
how to use cookies in this article. However, this does not mean cookies are completely useless on the modern-day web — they are still used commonly to store data related to user personalization and state, e.g. session IDs and access tokens. For more information on cookies see our Using HTTP cookies article. The "easier" features we mentioned above are as follows: You'll learn more about these APIs below. The
Use
of Cache and Service Workers is an advanced topic, and we won't be covering it in great detail in this article, although we will show an example in the Offline asset storage section below. The Web Storage API is very easy to use — you store simple name/value pairs of data (limited to strings, numbers, etc.) and retrieve these
values when needed. Let's show you how: Storage.getItem() method takes one parameter — the name of a data item you want to retrieve — and returns the item's value. Now type these lines into your JavaScript console: Upon typing in the second line, you should see that the myName variable now contains the value of the
name data item. Storage.removeItem() method takes one parameter — the name of a data item you want to remove — and removes that item out of web storage. Type the following lines into your JavaScript console: The third line should now return null — the name item no longer exists in the web storage. The data persists!One key feature of web storage is that the data persists between page loads (and even when the browser is shut down, in the case of
Separate storage for each domainThere is a separate data store for each domain (each separate web address loaded in the browser). You will see that if you load two websites (say google.com and amazon.com) and try storing an item on one website, it won't be available to the other website. This makes sense — you can imagine the security issues that would arise if websites could see each other's data! A more involved exampleLet's apply this new-found knowledge by writing a working example to give you an idea of how web storage can be used. Our example will allow you enter a name, after which the page will update to give you a personalized greeting. This state will also persist across page/browser reloads, because the name is stored in web storage. You can find the example HTML at personal-greeting.html — this contains a website with a header, content, and footer, and a form for entering your name.
Let's build up the example, so you can understand how it works.
Your example is finished — well done! All that remains now is to save your code and test your HTML page in a browser. You can see our finished version running live here. Note: In the line Storing complex data — IndexedDBThe IndexedDB API (sometimes abbreviated IDB) is a complete database system available in the browser in which you can store complex related data, the types of which aren't limited to simple values like strings or numbers. You can store videos, images, and pretty much anything else in an IndexedDB instance. However, this does come at a cost: IndexedDB is much more complex to use than the Web Storage API. In this section, we'll really only scratch the surface of what it is capable of, but we will give you enough to get started. Working through a note storage exampleHere we'll run you through an example that allows you to store notes in your browser and view and delete them whenever you like, getting you to build it up for yourself and explaining the most fundamental parts of IDB as we go along. The app looks something like this:
Each note has a title and some body text, each individually editable. The JavaScript code we'll go through below has detailed comments to help you understand what's going on. Getting started
Database initial set upNow let's look at what we have to do in the first place, to actually set up a database.
So with this database schema set up, when we start adding records to the database, each one will be represented as an object along these lines:
Adding data to the databaseNow let's look at how we can add records to the database. This will be done using the form on our page. Below your previous event handler, add the following line, which sets up a
Now let's define the
This is quite complex; breaking it down, we:
Displaying the dataWe've referenced
Again, let's break this down:
Deleting a noteAs stated above, when a note's delete button is pressed, the note is deleted. This is achieved by the
So that's it! Your example should now work. If you are having trouble with it, feel free to check it against our live example (see the source code also). Storing complex data via IndexedDBAs we mentioned above, IndexedDB can be used to store more than just text strings. You can store just about anything you want, including complex objects such as video or image blobs. And it isn't much more difficult to achieve than any other type of data. To demonstrate how to do it, we've written another example called IndexedDB video store (see it running live here also). When you first run the example, it downloads all the videos
from the network, stores them in an IndexedDB database, and then displays the videos in the UI inside Let's walk through the most interesting parts of the example. We won't look at it all — a lot of it is similar to the previous example, and the code is well-commented.
Offline asset storageThe above example already shows how to create an app that will store large assets in an IndexedDB database, avoiding the need to download them more than once. This is already a great improvement to the user experience, but there is still one thing missing — the main HTML, CSS, and JavaScript files still need to be downloaded each time the site is accessed, meaning that it won't work when there is no network connection.
This is where Service workers and the closely-related Cache API come in. A service worker is a JavaScript file that is registered against a particular origin (web site, or part of a web site at a certain domain) when it is accessed by a browser. When registered, it can control pages available at that origin. It does this by sitting between a loaded page and the network and intercepting network requests aimed at that origin. When it intercepts a request, it can do anything you wish to it (see use case ideas), but the classic example is saving the network responses offline and then providing those in response to a request instead of the responses from the network. In effect, it allows you to make a web site work completely offline. The Cache API is another client-side storage mechanism, with a bit of a difference — it is designed to save HTTP responses, and so works very well with service workers. A service worker exampleLet's look at an example, to give you a bit of an idea of what this might look like. We have created another version of the video store example we saw in the previous section — this functions identically, except that it also saves the HTML, CSS, and JavaScript in the Cache API via a service worker, allowing the example to run offline! See IndexedDB video store with service worker running live, and also see the source code. Registering the service workerThe first thing to note is that there's an extra bit of code placed in the main JavaScript file (see index.js). First we do a feature detection test to see if the
Note: The given path to the Installing the service workerThe next time any page under the service worker's control is accessed (e.g. when the example is reloaded), the service worker is installed against that page, meaning that it will start controlling it. When this occurs, an Let's look at an
example, in the sw.js file (the service worker). You'll see that the install listener is registered against Inside the Here is where we see the Cache API in action. We use the
That's it for now, installation done. Responding to further requestsWith the service worker registered and installed against our HTML page, and the relevant assets all added to our cache, we are nearly ready to go. There is only one more thing to do: write some code to respond to further network requests. This is what the second bit of code in Inside the handler we first log the URL of the requested asset. We then provide a custom response to the request, using the Inside this block we use
If a match is found, we return it as the custom response. If not, we fetch() the response from the network and return that instead.
And that is it for our service worker. There is a whole load more you can do with them — for a lot more detail, see the service worker cookbook. Many thanks to Paul Kinlan for his article Adding a Service Worker and Offline into your Web App, which inspired this example. Testing the example offlineTo test our service worker example, you'll need to load it a couple of times to make sure it is installed. Once this is done, you can:
If you refresh your example page again, you should still see it load just fine. Everything is stored offline — the page assets in a cache, and the videos in an IndexedDB database. SummaryThat's it for now. We hope you've found our rundown of client-side storage technologies useful. See alsoIn this moduleHow can we store data in JavaScript without database?You can use web storage. From W3Schools: With web storage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request.
Can we store data using JavaScript?JavaScript allows us to store data in the browser using local storage API. Here, you can use LocalStorage and SessionStorage . The objects let us store data (in key/value pairs) and update it from the browser's storage. To view the data, open your browser.
What is used to store data temporarily?A computer's memory is used for temporary storage, while a computer's hard drive is used for permanent storage. ... A computer's memory is also called RAM which is an acronym for Random Access Memory. A computer's memory is where information is temporarily stored while it is being accessed or worked on.
How does JavaScript store data in browser cache?Storing simple data — web storage. First, go to our web storage blank template on GitHub (open this in a new tab).. Open the JavaScript console of your browser's developer tools.. All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage .. |