Search code examples
firefoxgreasemonkey

Can I keep stored data for a Greasemonkey script even when it's uninstalled?


I've written a Greasemonkey script that saves preferences using GM_SetValue. Sometimes, if there's an issue with the script, I advise users to reload the script by removing it and re-installing. This blows away the stored values for the script, which is very inconvenient for the user.

Is there a better way to store this information? The state I need to store is per-page, using the URL as a key for GM_SetValue, if that makes any difference.


Solution

  • Yes, you can copy the SQLite file that stores GM_setValue data and preserve that information.

    To find the data:

    1. Go to your Firefox profile folder.
    2. Enter the gm_scripts folder therein.
    3. The appropriate file will be named based on the script name and will have the extension .db.
      For example if the script is named:
      // @name _Zombie GM_setValue fun
      Then the SQLite file will be named:
      _Zombie_GM_setValue_fun.db


    If you move or copy this file to a safe place, then do whatever to the script, then copy the file back; your data will be preserved. (As long as you don't change the script's @name or @namespace.)
    You don't have to close Firefox while you do this, but I would -- to guard against edge-case mishaps.

    Example script:

    // ==UserScript==
    // @name     _Zombie GM_setValue fun
    // @include  https://stackoverflow.com/questions/28498610/*
    // @grant    GM_getValue
    // @grant    GM_setValue
    // ==/UserScript==
    
    var lastVal = GM_getValue ("LastValue");
    var newVal  = prompt (
        'The last value was "' + (lastVal || "{not set}") + '". Enter a new value:',
        ''
    );
    if (newVal)
        GM_setValue ("LastValue", newVal);
    

    Test sequence:

    1. Install the script.
    2. Reload this very page (stackoverflow.com/questions/28498610/).
    3. You'll see The last value was "{not set}". Enter a new value:.
    4. Enter Save me.
    5. Reload the page.
    6. You'll see The last value was "Save me". Enter a new value:
    7. Copy _Zombie_GM_setValue_fun.db to a safe place.
    8. Uninstall the script and (optionally) restart Firefox.
    9. Reinstall the script.
    10. Load the page and you'll see "{not set}" as in step 3.
    11. Copy the saved _Zombie_GM_setValue_fun.db back to the gm_scripts folder, overwriting the newer _Zombie_GM_setValue_fun.db if it is present.
    12. Reload the page you'll see Save me as in step 6.