Set javascript global variables across multiple pages

33,012

Solution 1

The short answer is:

localStorage.setItem("bar", foo);

and then:

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

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

Solution 2

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/

Solution 3

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

Share:
33,012
user2818066
Author by

user2818066

Updated on May 06, 2020

Comments

  • user2818066
    user2818066 about 4 years

    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?

  • user2818066
    user2818066 about 10 years
    Thanks for the info. What about on browser that does not support html5?
  • nicholas
    nicholas about 10 years
    That's what servers are for.
  • Yuriy Galanter
    Yuriy Galanter about 10 years
    @user2818066 browsers down to IE8 support localstorage. If you need to go lower than IE8 - you've got problem.
  • Pierre
    Pierre over 7 years
    pretty cool tool that yes!