Search code examples
javascriptdomgoogle-chromeuserscripts

LocalStorage with Userscript on Chrome


I badly need someway to store data within an edited DOM of a page, and then access it from the userscript. Also, I need this to be done on Google Chrome. This is my current script, but I can't get it working:

The internal script:

var o_shout_tabs=unsafeWindow.localStorage.getItem('va_shout_tabs')||true;
var o_profile_damage=unsafeWindow.localStorage.getItem('va_profile_damage')||true;
var o_allies=unsafeWindow.localStorage.getItem('va_allies')||true;

The edited DOM:

<script type="text/javascript">
     function saveData(a,b){
         var unsafeWindow=this['unsafeWindow']||window;
         unsafeWindow.localStorage.setItem('va_'+a,b);
     }
</script>
<input type="checkbox" value="1" onclick="saveData('shout_tabs', this.checked)"/>
<input type="checkbox" value="1" onclick="saveData('profile_damage', this.checked)"/> 
<input type="checkbox" value="1" onclick="saveData('allies', this.checked)"/>

However, this always returns false when I test with for example o_shout_tabs==true, no matter the input (although, if it hasn't received an input at all, it returns true).


Solution

  • What always returns false?

    Anyway, the init logic is off. For boolean values, code like this:

    var o_shout_tabs=unsafeWindow.localStorage.getItem('va_shout_tabs')||true;
    

    will always return true or a string.

    Use this code:

    function getBoolFromStorageDefaultTrue (varName) {
        var val = localStorage.getItem (varName);
        if (val == null)
            return true;
        return (  (val == "false")  ?  false  :  true  );
    }
    
    var o_shout_tabs        = getBoolFromStorageDefaultTrue ('va_shout_tabs');
    var o_profile_damage    = getBoolFromStorageDefaultTrue ('va_profile_damage');
    var o_allies            = getBoolFromStorageDefaultTrue ('va_allies');