1

I have some HTML pages that open each other by: window.location.href = "anotherpage.html"; I have a JS int variable and i need to keep it global (if page1 opens page2 and later, page2 opens page1 the var should have the same value and not "reset").

How can i do that?

alex
  • 479,566
  • 201
  • 878
  • 984
  • Like Stephen P said in a comment below [Local Storage](http://diveintohtml5.info/storage.html) would be a really easy solution to this. – CaffeineAddiction Apr 16 '14 at 01:09

2 Answers2

2

You can use local storage. Some functions to make it handy:

function enableLSvars() {
    if (typeof(Storage) === "undefined") throw { message : 'Local storage must be enabled to use this.' }
    this.LS_getValue = function (key, def) { return localStorage[key] || def; }
    this.LS_setValue = function (key, value) { return localStorage[key] = value; }
    this.LS_deleteValue = function (key) { return delete localStorage[key]; }
}

In page where you want to save a variable call for:

LS_setValue(yourVar, "yourValue");

To retrieve the value later, use:

LS_getValue(yourVar);

AlexTR
  • 772
  • 8
  • 14
0

As others says, you need to store your data to some database when transition.

But if you implement SPA (Single-Page Application) with JavaScript framework, such as AngularJS, jQueryMobile and so on, you can easily keep javascript variable even if the page changes. These framework does not adopt simple linking to another page.

These framework keep a root page and fetch another page's DOM with Ajax, then build another page on the root page. As a result, JavaScript variable loaded in the root page survives and can be accessed from another page.

AngularJS

jQueryMobile

Please look this AngularJS demo in the blog post. No database is used in this demo.

Tamura
  • 1,788
  • 1
  • 14
  • 10