Save and load more reliably with in userscript, maybe.

So, been messing around with userscript lately, in tampermonkey. And hence had a few problems saving and loading with GM_setValue and GM_getValue. There are a couple of scrips out there to sort this for you, but none that i was able to get to work. So I’ve wrapped my own version up, which also compresses via LZstring. (google it).

d.save(“float”, 12.34);
d.load(“float”);

For my purpose i found it most reliable to include whole libraries inside an anonymous function together with any code. This seem to help som scope issues I had, at a potential cost of performance (none that I have noticed tho). I’ve also included waitForKeyElement, cause it is nice to have at hand.

In principle the functions just wrap anything into an object (which you dont really need to do, but wth), stringifies, saves MD5, compresses, saves. And vice versa.

It does not work as expected with any data. Seems safe for sring, int, float, bool, undefined, null, objects and arrays. Does not work for NaN or functions as far as i can tell. Also not sure about “new Date()” objects and the like.

However for all intents and purposes it seem reliable enough.

The whole ting is included in a file further down, with some examples. Here are the main methods themselves.

var d = {
    save : function(key, value){
        if (key){
            var wrobj = {value: value};
            if (Number.isNaN(value)){wrobj = {value: "_NaN_"}};
            try {
                var strng = JSON.stringify(wrobj);
            } catch (e){
                console.log(e);
                return;
            }
            var hash = MD5(strng);
            strng = LZString.compressToBase64(strng);
            GM_setValue(key, strng);
            GM_setValue((key + "hash"), hash);
        }
    },
    load : function(key){
        if (key){
            if (GM_getValue(key)){
                var strng = GM_getValue(key);
                strng = LZString.decompressFromBase64(strng);
                var storedhash = GM_getValue(key + "hash");
                var newhash = MD5(strng);
                if (storedhash === newhash){
                    try {
                        var value = JSON.parse(strng);
                    } catch (e){
                        console.log(e);
                        return;
                    }
                    return value.value;
                }
            } else {
                return false;
            }
        }
    }
}Code language: JavaScript (javascript)