MirroredFate MirroredFate - 1 year ago 119
Javascript Question

How to add custom global javascript to mediawiki

How can I add a custom javascript file (let's say

) to a mediawiki installation?

For instance, if I put
under the folder
, how do I get that to be loaded on every page?

I am not trying to do this as part of an extension, and I would prefer to keep my changes in

Answer Source

As garryp has already suggested, you can put the JavaScript code into MediaWiki:Common.js. Note that this is not a file, but simply a page you can edit (as an administrator) on your wiki. For example, here's the MediaWiki:Common.js page on the English Wikipedia.

JavaScript code from Common.js is only loaded if the $wgUseSiteJs is enabled. However, this is the default setting, so it should work unless you've deliberately disabled it by adding a line like $wgUseSiteJs = false; into your LocalSettings.php file.

It's also possible to load JavaScript code from a file using ResourceLoader, but this is a bit more complicated. Still, just as a quick example, if you had, say, files named foo/bar.js and foo/baz.js in your main MediaWiki directory, you could load them by adding the following code into your LocalSettings.php file:

// register a ResourceLoader module...
$wgResourceModules['custom.foo.whatever'] = array(
    'scripts' => array( 'foo/bar.js', 'foo/baz.js' ),
    // could e.g. add dependencies on core modules here
// ...and set up a hook to add it to every page
function addMyCustomScripts( &$out ) {
    $out->addModules( 'custom.foo.whatever' );
    return true;
$wgHooks['BeforePageDisplay'][] = 'addMyCustomScripts';

Basically, this method is mostly useful for extension authors, who can use it to load CSS and JS code as needed. See the $wgResourceModules and BeforePageDisplay documentation for more details, including additional module options (and core modules).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download