Search code examples
mediawikimediawiki-extensionsmediawiki-templates

Modify MediaWiki Search Form


Is there a way to modify the MediaWiki search form in the page header other than by editing Vector.php?

Basically, I would like to change/extend the markup of the the HTML form and add a JavaScript listener for Ajax calls.

Unfortunately, I can't seem to be able to find an appropriate hook.


Solution

  • That's not easily possible, if you want to change the HTML. But to add a JavaScript listener you usually don't need to add something directly to the input where you want to listen for events.

    You could, e.g., use jQuery to add a listener to the search input. For this you could create a new extension (read this manual for a quick start). In your extension, you create a new resource module:

    {
        "@comment": "Other configuration options may follow here"
        "ResourceFileModulePaths": {
            "localBasePath": "",
            "remoteSkinPath": "ExampleExt"
        },
        "ResourceModules": {
            "ext.ExampleExt.js": {
                "scripts": [
                    "resources/ext.ExampleExt.js/script.js"
                ]
            }
        },
        "@comment": "Other configuration options may follow here"
    }
    

    Now, you can add the script file, which you defined in the module:

    ( function ( $ ) {
        $( '#searchInput' ).on( 'change', function () {
            // do whatever you want when the input
            // value changed
        }
    }( jQuery ) );
    

    The code in the function (in the second parameter of the on() function) will run whenever the value of the search input changes.

    Now, you only need to load your module when MediaWiki output's the page. The easiest way is to use the BeforePageDisplay hook:

    Register the hook handler:

    {
        "@comment": "Other configuration options may follow here"
        "Hooks": {
            "BeforePageDisplay": [
                "ExampleExtHooks::onBeforePageDisplay"
            ],
        },
        "@comment": "Other configuration options may follow here"
    }
    

    Handle the hook (in ExampleExtHooks class, which needs to be created and added to the Autoload classes):

    public static function onBeforePageDisplay( OutputPage &$output, Skin &$skin ) {
        $output->addModules( array(
            'ext.ExampleExt.js',
        ) );
        return true;
    }