4

I want to store global variables in javascript array to make them available for multiple pages.

I know that cookies or localstorage can do similar things. But I want to store lots of information therefore it would be better if I can figure out a way to store them in javascript array.

For example, in html 1 file

<head>
    <title>Global javascript example</title>
</head>
<body>
    <button type="button" onclick="global_var['a']['a']=1;"> a,a set to 1  </button>  
    <br/>                              
    <button type="button" onclick="global_var['a']['b']=1;"> a,b set to 1  </button>             
    <br/>                              
    <button type="button" onclick="alert(global_var['a']['b']);"> echo  a,b   </button>  
</body>

Now in another html file or the same page after refresh, I want to access the global variable:

<head>
    <title>Global javascript example</title>
</head>
<body>                            
    <button type="button" onclick="alert(global_var['a']['b']);"> echo a,b </button>               
</body>

Is there any way to implement this other than using cookies?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
user2818066
  • 618
  • 2
  • 8
  • 19

3 Answers3

24

The short answer is:

localStorage.setItem("bar", foo);

and then:

var foo = localStorage.getItem("bar");

The long answer is http://diveintohtml5.info/storage.html

nicholas
  • 14,184
  • 22
  • 82
  • 138
4

You can store array (or any other object) into local storage. All you need is JSON.stringify to convert any object (including array) into string to place into the storage and JSON.parse to convert it back into the object after retrieving it from the storage.

Here's quick reference: http://samcroft.co.uk/2013/using-localstorage-to-store-json/

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
2

Consider using localStorage as nicholas mentioned which holds your comfortable amount of memory like 5MB to unlimited depending on browser capabilities.

If you are still not convinced with cookies or localStorage which are straightforward methods try using libraries like sessvarsJS

A detailed tutorial & demo can be found at Session variables without cookies

Community
  • 1
  • 1
nehem
  • 12,775
  • 6
  • 58
  • 84