0

I'm working on a web application, in which the values of an array is pushed through a JavaScript function call of one HTML page, and the same array needs to be accessed from another JavaScript function called by a different HTML page.

The code at the moment is:

var global_array = [];

function pushIntoArray(){
  global_array.push({"id":1, "value":"example1"}, {"id":2, "value":"example2"});
}

function getArrayValues(){
   console.log(global_array);
}

The first function is called through a button click, the second function is called on a different page on page load.

The problem I'm having is that when the second function getArrayValues() is called on a different HTML page, the values that were previously pushed into the array "global_array" disappears.

What is the most efficient way solve this? Thanks.

  • My first guess is that when you reload the page i.e going to another page, your js file is reloaded too, so whatever values you had will be erased because your variable global_array is reset to an empty array – achref Mar 01 '17 at 19:49
  • I have voted to reopen the question, because it is not only about sharing data between pages, it is about sharing functionality as well. – Lajos Arpad Mar 01 '17 at 19:53

2 Answers2

0

You should have a look to localStorage

window.localStorage.setItem("array", JSON.stringify(array)); // Saving
var cart = JSON.parse(window.localStorage.getItem("array")); // Retrieving
  • When I used JSON.parse(), the browser console outputs error "unexpected token o in json at position 1". If I remove the JSON.parse() leaves only window.localStorage.getItem,("array"), the browser outputs [object Object] but not the original json values. Any idea on how to fix this? I'm testing it on Google Chrome and Microsoft Edge. – Andrew Zhao Mar 01 '17 at 21:22
0

You can use localStorage where you can add items on a page and load them on the second page.

localStorage.setItem("global_array", JSON.stringify(global_array));
localStorage.setItem("pushIntoArray", pushIntoArray + "");

On the other page you can do this:

window["global_array"] = eval("(" + localStorage.getItem("global_array") + ")");
window["pushIntoArray"] = eval(localStorage.getItem("pushIntoArray"));

However, you will need to load the first page to make sure your settings exist in the second page.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175