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

前端 未结 3 2035
执笔经年
执笔经年 2021-01-13 10:17

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(){         


        
3条回答
  •  难免孤独
    2021-01-13 10:52

    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=; 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];
            }
        }
    }
    

提交回复
热议问题