Search code examples
greasemonkey

Create a "config" or "options" page for a Greasemonkey script


I've written a simple Greasemonkey script, and I'm trying to create a "config" page for this script (like the one that is used for Google Chrome extensions. ) Would there be any way to create a config page for a userscript, like the "options" pages for Google Chrome extensions? There isn't any way to include an .html page as part of a Greasemonkey script (as far as I know), so I'm looking for other options.

// ==UserScript==
// @name       Redirector
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @match      http://*/*
// @copyright  2012+, You
// @run-at document-start
// ==/UserScript==

redirectToPage("http://www.youtube.com/", "http://www.google.com");

function redirectToPage(page1, page2){
if(window.location.href.indexOf(page1) != -1){
    window.location.href = page2;
}
}

Solution

  • There are a few libraries which provide config pages for userscripts:

    1) GM_config

    Example GM_config dialog

    2) MonkeyConfig

    Example MonkeyConfig dialog

    3) GM_registerMenuCommand Submenu JS Module


    The usage varies per library, but typically you grant the permissions they need such as GM_getValue and GM_setValue, and require the library via the @require directive, e.g.:

    // ==UserScript==
    // @name          My Userscript
    // @description   An example userscript with a config page
    // @version       0.0.1
    // @require       https://www.example.com/lib/myconfig.js
    // @grant         GM_getValue
    // @grant         GM_setValue
    // @grant         GM_addStyle
    // @grant         GM_registerMenuCommand
    // ==/UserScript==
    
    const config = new MyConfig({ ... })
    

    You then register a menu command which opens the config page/dialog, e.g.:

    GM_registerMenuCommand('Configure My Userscript!', () => {
        config.open()
    })
    

    In the case of MonkeyConfig, it can register the command for you:

    const config = new MonkeyConfig({
        title: 'Configure My Userscript!',
        menuCommand: true,
        // ...
    })
    

    For advanced uses, the configurator may allow listeners to be registered for the close/cancel/save events, as well as providing control over the CSS, and other options. Detailed instructions can be found on the GM_config wiki and the MonkeyConfig homepage.