thatOneGuy
thatOneGuy

Reputation: 10612

How would I save a JS variable so it can be used on another HTML page

I have two HTML pages. On the first page I add values to an array.

thisArray.push("new value");

On the second HTML page I want to print this array to a textArea

for(i=0; i<thisArray.length;i++){

        var thisName = thisArray[i];
        document.getElementById('listOfNames').innerHTML +=  thisName + '\n';    

    }

But when I change the page obviously the browser wont know about the other variable. What's the best way to do this ?

I thought of saving the value locally? Is this the best way?

Upvotes: 1

Views: 52

Answers (5)

Wenceslao Negrete
Wenceslao Negrete

Reputation: 556

You have at least, two options to do what you want, one is pass that variable on the url query like:

www.mypage.com?my_javascript_var=12345

Another option is using localstorage

localStorage.setItem('itemName', varToBeSaved);

then, to get the variable back on any page

var mySavedVar = localStorage.getItem('itemName');

Upvotes: 1

BlaiV
BlaiV

Reputation: 21

Check out this library which allows you to set and read javascript cookies easily.

https://github.com/js-cookie/js-cookie

Example:

Set cookie on first page:

Cookies.set('thisArray', JSON.stringify(thisArray));

Read cookie on second page:

var thisArray = Cookies.getJSON('thisArray');

Upvotes: 1

dimlucas
dimlucas

Reputation: 5141

You can use localStorage.setItem(key,value)

Upvotes: 1

Nermin
Nermin

Reputation: 6100

You can use localStorage to persist the value,

localStorage.setItem('itemName', itemValue);

then to fetch the item just use

localStorage.getItem('itemName');

Upvotes: 1

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83438

Use window.localStorage.

https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

Example:

 window.localStorage.myArray = JSON.stringify(arrayData)

And then parse JSON when read the data on another page.

Upvotes: 1

Related Questions