Persist javascript variables across pages?
JavascriptJavascript Problem Overview
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...?
Javascript Solutions
Solution 1 - Javascript
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 - Javascript
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 - Javascript
I would recommend you to give a look to this library:
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 - Javascript
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 - Javascript
You can persist values using HTML5 storage, Flash Storage, or Gears. The dojo storage library provides a nice wrapper for this.
Solution 6 - Javascript
I recommend web storage. Example:
// Storing the data: localStorage.setItem("variableName","Text"); // Receiving the data: localStorage.getItem("variableName");
Just replace variable
with your variable name and text
with what you want to store. According to W3Schools, it's better than cookies.