Persist javascript variables across pages? [duplicate]

Is there a way we can persist javascript variables across various pages? Suppose in Page A I am setting window.someVar = 5. Then I move to Page B, via clicking a hyperlink in A, and do something like alert(window.someVar) -- I should get a message box displaying 5. Is there a technique to persist someVar as such...?


Solution 1:

You could use the window’s name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Solution 2:

For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.

http://www.w3.org/TR/2009/WD-webstorage-20091222/

https://www.w3.org/TR/webstorage/. (second edition)

Here are some sample code for setting and getting the values using sessionStorage and localStorage :

 // HTML5 session Storage
 sessionStorage.setItem("variableName","test");
 sessionStorage.getItem("variableName");


//HTML5 local storage 
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");

Solution 3:

I would recommend you to give a look to this library:

  • PersistJS

I really like it, it supports a variety of storage backends (from cookies to HTML5 storage, Gears, Flash, and more...), its usage is really transparent, you don't have to know or care which backend is used the library will choose the right storage backend depending on the browser capabilities.

Solution 4:

Yes, using Cookies. But be careful, don't put too much in them (I think there is a limit at 4kb). But a few variables are ok.

If you need to store considerably more than that, check out @Annie's great tips in the other answer. For small time data storage, I would say Cookies are the easiest thing.

Note that cookies are stored client side.

Solution 5:

You can persist values using HTML5 storage, Flash Storage, or Gears. The dojo storage library provides a nice wrapper for this.