简体   繁体   中英

How to save the state of a javascript variable that is used in multiple html pages

I am trying to make an application in phonegap. I have made a custom.js javascript file which have some functions as

function func1(){....}
function func2(){....}

All these functions will be used in two different html pages. In first HTML page,I am using a variable in func1 which is doing some operation. In second page, I want to access it in func2 in the state in which he was in func1. But i am unable to do it. I am including custom.js in both html pages. I have read that javascript files get reset/refresh when used in multiple pages. Can anybody give me an example that how to save the state of variable in func1 and then access that variable in func2 (in different HTML page) in the state in which he was in func1. i have also read about view state. but it is not working either for me. Please help...

Store the values in localstorage and reference it from there.

function first() {
    localStorage.setItem('myItem', "something you want to store");
}

function second() {
    myValue = null;
    if (localStorage.getItem('myItem')) {
        myValue = localStorage.getItem('myItem');
    }
}

in modern browsers you can use localStorage for that

var get = function (key) {
  return window.localStorage ? window.localStorage[key] : null;
}

var put = function (key, value) {
  if (window.localStorage) {
    window.localStorage[key] = value;
  }
}

use get and put to store value to the local storage of most modern browsers..

The easier and preferred method would be to use window.localStorage for storing site wide variables. To accommodate older browsers as well, you can maybe consider having cookies as a secondary storage location.

// credits to http://mathiasbynens.be/notes/localstorage-pattern
var hasStorage = (function() {
      try {
        localStorage.setItem(mod, mod);
        localStorage.removeItem(mod);
        return true;
      } catch(e) {
        return false;
      }
    }());

function setSiteWideValue(_key, _value) {
    if(hasStorage) {
        localStorage[_key] = _value;
    }
    else {
        document.cookie = _key+'='+_value+'; expires=<date-here>; path=/; ;domain=<.yourdomain>';
    }
}

function getSiteWideValue(_key) {
    if(hasStorage) {
        return localStorage[_key];
    }
    else {
        if(document.cookie.indexOf(_key+'=') != -1) {
            return document.cookie.split(_key+'=')[1].split(';')[0];
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM