Saving values โ€‹โ€‹in a JavaScript object via browser update

I created a JavaScript object.

var myObj = {}; 

Now that the user is playing with the application, we assign some values โ€‹โ€‹to this object.

 myObj['Name'] = 'Mr. Gates'; myObj['Age'] = 58; ... ... ... myObj['Role'] = 'CEO'; 

But whenever the page is refreshed, the object loses its meaning.

Is there a way to use HTML 5 \ or any other method to save these values โ€‹โ€‹when refreshing the page.

+6
source share
1 answer

Yes, you have two main options:

  • Use of cookie. Cookies are easy to install from JavaScript, but a little pain is read. You said you were using jQuery; There are several jQuery plugins that make cookies a lot easier. If you are looking for a "jQuery cookie plugin" you will find them.

  • Using web storage that is supported by all major browsers, even IE8 . You have two options: the Session storage, which is saved only for this โ€œsessionโ€, and the โ€œlocalโ€ storage, which is stored until the user clears it or the browser decides that it needs this room for something yet.

This second option is pretty easy to use, you can store things using strings in JSON format (the JSON object is also supported by all major browsers ):

Saving your object:

 localStorage.yourObject = JSON.stringify(obj); 

Retrieving your object (for example, when loading a page) or an empty object if you do not save it:

 obj = JSON.parse(localStorage.yourObject || "{}"); 

In the above example, localStorage is the variable (and underlying implementation) provided by the browser for local storage. Instead, you could use sessionStorage if you want session storage.

Here is an example of local storage: Live Copy

 <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <meta charset=utf-8 /> <title>Local Storage</title> </head> <body> <label><code>Name</code> property for our object: <input type="text" id="txtName"> </label> <script> (function() { var txtName = $("#txtName"); var obj = JSON.parse(localStorage.yourObject || '{"Name": ""}'); txtName.val(obj.Name); // This is obviously hyperactive: txtName.on("change keypress keyup blur paste click", function() { obj.Name = txtName.val(); localStorage.yourObject = JSON.stringify(obj); }); })(); </script> </body> </html> 
+12
source

All Articles