ResourceLoader/Default modules

From MediaWiki.org
Jump to: navigation, search
Language: English  • 中文
shortcut: RL/DM

Contents


This page intends to list, document, explain and give examples for all the libraries, plugins and scripts present in MediaWiki's /resources by default, as found in the latest development version of MediaWiki ("git master"). This may vary from the stable release version of MediaWiki. However, this list is currently incomplete.

The order of the modules should be kept similar to their definition in Resources.php. Within the module documentation, the order of the headings for objects should be by order within the script file or by alphabet (whichever makes sense). If a module has only one object, with the same name as the module, this should be documented, but a separate heading is not necessary.

There is now JSDuck documentation for these modules. It does not include all of the below (e.g. the examples are not the same), but is likely to be more up to date, since it is compiled automatically from comments in the source.

MediaWiki[edit | edit source]

mediawiki[edit | edit source]

This is the main JavaScript module, mediawiki. It sets the window.mediaWiki object, with window.mw as an alias. Alias mw is available everywhere and should be used.

mediaWiki.config[edit | edit source]

For a complete list of configuration values in mw.config, check out Manual:Interface/JavaScript.

An instance of the Map class that is global by default for backwards compatibility (in 1.17) and contains the wgVars such as wgSiteName, wgArticleId etc.

// Check existence
if ( mw.config.exists( 'wgGlobalGroups' ) ) {
  // CentralNotice has registered this variable...
}
 
// Or just a plain access for comparison
// (no need to check exists first, it falls back to null)
if ( mw.config.get( 'wgPageName' ) === 'ResourceLoader' ) {
  // Do stuff...
}
 
// Access multiple ones for use throughout a larger code base
var conf = mw.config.get([
        'wgServer',
        'wgPageName',
        'wgCanonicalSpecialPageName',
        'wgUserLanguage'
]);
 
if ( conf.wgCanonicalSpecialPageName === 'Blankpage' ) {
  // Do stuff...
}

mediaWiki.hook[edit | edit source]

mw.hook.add, mw.hook.fire, mw.hook.remove
A framework for registering and firing events in JavaScript (as opposed to doing everything on document ready).

See the code for more information and examples.

mediaWiki.html[edit | edit source]

mw.html.escape
Escape a string for HTML. Converts special characters to HTML entities.
mw.html.escape( '< > \' & "' );
// Returns: &lt; &gt; &#039; &amp; &quot;
mw.html.element
Creates an HTML string, with safe escaping.
// shortcut h
var h = mw.html;
var myElement = h.element(
        'div', // tagName
        {}, // attributes
        // content:
        new h.Raw(      // We don't want to escape the return of h.element(), instead add it raw
                        // Without this the result would be '<div>&lt;img src=&quot;&amp;lt;&quot;/&gt;</div>'
                h.element(
                        'img', // tagName
                        { src: '<'      } // attributes
                )
        )
);
 
// myElement is '<div><img src="&lt;"/></div>' (as a string)
var h = mw.html;
var loaderContainer = h.element( 'div', { id: 'ext-foobar-loader' },
        new h.Raw( h.element( 'img', {
                src: mw.config.get( 'stylepath' ) + '/common/images/ajax-loader.gif',
                title: 'Loading...'
                }
        ) )
);
 
// loaderContainer is '<div id="ext-foobar-loader"><img src="/w/skins/common/images/ajax-loader.gif" title="Loading..."/></div>'

mediaWiki.message[edit | edit source]

See also Manual:Messages API#Using messages in JavaScript

Note that loading the mediawiki.jqueryMsg module significantly changes the behavior of this module. See above link.

Returns a new instance of Message. mediaWiki.msg() is a shortcut to this with output using the text format (however, without jqueryMsg, this is equivalent to the plain format). See Manual:Messages API#Using messages in JavaScript for information about using PLURAL, GENDER, and more advanced message features in JavaScript.

key
Key of the message
parameter_1
(optional) this argument and any later ones will be passed to the Message constructor as the parameter array (to do replaces for $1, $2 etc.)
/**
 * Suppose we have a message key "user-welcome" with value
 * "Hello $1. Welcome to $2. Last visit by $1: $3".
 */
 
// Get instance of Message
var welcome = mw.message( 'user-welcome', 'Krinkle', 'Wikipedia', 'now' );
 
// Get it as a plain string (other formats are 'text', 'parse', and 'escaped')
welcome.format = 'plain';
welcome.toString();
 
// Shortcut for the above
welcome.plain();
 
// Returns: "Hello Krinkle. Welcome to Wikipedia. Last visit by Krinkle: now"

mediaWiki.msg[edit | edit source]

This is a shortcut for creating an instance of Message via mediaWiki.message() and returning .toString();

It is semi-deprecated.

mediaWiki.loader[edit | edit source]

mw.loader.addSource[edit | edit source]

Since MW 1.19 r93247 Keep track of origin in the client-side registry of ResourceLoader by adding an internal source id (lowercase a-z string, first parameter) for a given loadscript property (second parameter). The internal registry will have an origin-key for each module (just like it has for groups). The execute-function will use the right loader-script as needed. And split up requests per module source.

mw.loader.addSource( 'mediawikiwiki', { loadScript: '//mediawiki.org/w/load.php' } );
mw.loader.getModuleNames[edit | edit source]

Since MW 1.19 r93653 Returns a copy of the full module list. If you just need to check on a module, consider mw.loader.getState instead.

mw.loader.getState[edit | edit source]

Returns the status of a module, 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'.

If a module is not in the registry at all, it will return null.

mw.loader.getVersion[edit | edit source]

Returns the version of a module, or null if it is not in the registry.

mw.loader.go[edit | edit source]

(deprecated in 1.19) No longer needed, mw.loader.load takes an array to load multiple modules in one request.

mw.loader.implement[edit | edit source]

Implements a module. This is used internally by ResourceLoader to implement every module.

mw.loader.load[edit | edit source]

Loads modules and other sources. It can be called with one or more modules by name. It can also load an external script or style URI beginning with either "http://", "https://" or "//" and a mime-type in the second argument (either "text/css" or "text/javascript"). If no mime-type is provided, "text/javascript" is assumed. mw.loader.load creates an asynchronous request, so if you need to run code that depends on a module, use mw.loader.using instead. If you want to load another script use jquery.getScript.

// Load one module by name. Will make 1 http request loading all JS, CSS of this and its dependencies. Will also load any needed interface messages to the memory of mw.msg
mw.loader.load( 'jquery.ui.datepicker' );
 
// Will do all resources stuff for multiple modules at once
mw.loader.load( ['jquery.ui.dialog', 'jquery.hoverIntent', 'mediawiki.foobar'] );
 
// Load an external javascript file as is
mw.loader.load( '//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400' );
 
// Load an external stylesheet as is
mw.loader.load( 'http://example.com/mystyles.css?color=blue', 'text/css' );

Note: mediaWiki.loader does not accept relative urls (see bug 34036) and differently from jQuery.getScript(), it doesn't support callback functions (aka "using") when used with URL (bug 25962).

mw.loader.register[edit | edit source]

Adds a module to the registry. This is used internally by the startup modules.

mw.loader.state[edit | edit source]

Changes the state of the module.

mw.loader.using[edit | edit source]

using can be called with two or three arguments (dependencies, function to execute when modules are successfully loaded, function on error). The error function takes two arguments, the error, and an array of dependencies that caused it.

mw.loader.using( 'jquery.colorUtil', function () {
  var curColor, newColor;
 
  // This function wil be called right away if the required modules are already loaded
  // Otherwise the module(s) are loaded and if all successful, the function is called
  curColor = 'rgb(70,140,210)';
  newColor = $.colorUtil.getColorBrightness( curColor, +0.2 );
  alert( '20% brigher than ' + curColor + ' is ' + newColor );
} );
mw.loader.version[edit | edit source]

(deprecated in 1.19) Use mw.loader.getVersion.

mw.loader.work[edit | edit source]

Processing function to load and execute modules

mediaWiki.log[edit | edit source]

This is is automatically loaded (only) in debug-mode (can be enabled with debug=true in the URL) and is an alternative to calling console.log() which would cause errors in browsers that don't have a console or don't have it enabled.

Calling this either pushes the messages to console if its available and have a logging facility, or adds it to an #mw-log-console if not (the element is created on the first call)

mw.log( 'To be logged message here' );

Note that different browsers and extensions may enable or disable different consoles and different logging facilities, and that they may or may not be visible even if they are used for logging purposes.

mediaWiki.Map[edit | edit source]

A reusable class to store, get and set a set of variables. The core uses this for mw.config and mw.user.options

When making an instance the function takes one parameter which affects whether the set will be made globally available (ie. as items of window) or local. By default this is false (not global) and will thus not not overwrite any global variables with the same name.

.values
An object containing all the variables. If 'global' was true during initialization, this is an alias to the window object.
.exists(key)
Function returns true if an entry with the key(s) exists, false otherwise
.get(key, fallback)
Returns the value of the key(s) or (optionally) the value of the second argument if the key does not exist (returns null if it doesn't exist and no fallback was provided)
.set(key, value)
Creates / Modifies one or multiple values

Examples

// Create a new map
var myMap = new mw.Map();
 
// Set a few values
myMap.set( {
  'name' : 'John Doe',
  'age' : 19,
  'planet' : 'Earth',
  'address' : 'Wikistreet 7, New York'
} );
 
// Set one more value
myMap.set( 'spouse', 'Jane Jackson' );
 
// Do something if a value is set
if ( myMap.exists( 'address' ) ) {
 alert( 'This map does have a value for "address". It is: ' + myMap.get( 'address' ) );
} else {
 alert( 'This map does not have a value for "address".' );
}
 
// Get multiple values
var NameAgeBirth = myMap.get( ['name', 'age', 'birthdate'] );
// NameAgeBirth.name is 'John Doe'
// NameAgeBirth.age is 19
// NameAgeBirth.birthdate is null

Address Book example

// Create a new map for this
var myAddressBook = new mw.Map();
 
// Define an object with name / address combinations
// This data could be coming from an AJAX request and/or from a database
var addresses = {
 'John Doe' : 'Wikistreet 7, New York',
 'Jane Jackson' : 'Oxfordstreet 21, London',
 'Max Heinz' : 'Rote strasse 201, Berlin'
}
 
// Set the variables in the addressbook
myAddressBook.set( addresses );
 
// A request could come in for a few names
var wantedNames = ['Max Heinz', 'George Johnson', 'Jane Jackson'];
 
// Check if they all have an entry
if ( !myAddressBook.exists( wantedNames ) ) {
 alert( 'One or more names do not have a known address' ); // In our example, there is no address for George Johson
}
 
wantedData = myAddressBook.get( wantedNames, '<em>Unknown location</em>' );
// wantedData['Jane Jackson'] is 'Oxfordstreet 21, London' 
// wantedData['George Johnson'] is '<em>Unknown location</em>'

mediaWiki.user[edit | edit source]

mw.user.anonymous[edit | edit source]

(deprecated in 1.20) Use mw.user.isAnon() instead.

mw.user.getName[edit | edit source]

Function returns the username if the user is logged in, or null if anonymous (logged out).

mw.user.id[edit | edit source]

Function returns the username if the user is logged in, or returns sessionId if the user is anonymous. Note this does not return the user's numeric ID in the wiki (which is available as a configuration value).

Prior to MediaWiki 1.22 the "id" for anonymous users was retained across sessions by a long-term cookie (bug 44327).

mw.user.isAnon[edit | edit source]

Function returns boolean indicating whether the user is anonymous (true) or logged in (false).

if ( !mw.user.isAnon() ) {
  alert( 'You are logged in as: ' + mw.user.getName() + '.' );
} else {
  alert( 'You are anonymous.' );
}
mw.user.name[edit | edit source]

(deprecated in 1.20) Use mw.user.getName() instead.

sessionId[edit | edit source]

When called for the first time generates a sessionId and sets a domain-wide cookie and returns the sessionId. When it's set already (ie. after calling it, or when it was set earlier this session on another page) returns just the sessionId.

alert( 'Your sessionId is: "' + mw.user.sessionId() + '" !' );

user.options[edit | edit source]

mw.user.options[edit | edit source]

Contains the preferences of the user, or the defaults when logged out. (mw.user.options is an instance of the mw.Map constructor)

// Get a preference option and use it directly
alert( 'According to the preferences, your gender is ' + mw.user.options.get( 'gender' ) );
 
// Get several preferences and compare them with $.compareObject
if ( $.compareObject( mw.user.options.get( ['diffonly', 'showhiddencats'] ), { diffonly: 0, showhiddencats : 0 } ) ) {
 // User's preferences match the object
} else {
 // User's preferences don't match the given set
}

user.tokens[edit | edit source]

mw.user.tokens[edit | edit source]

MediaWiki version: = 1.18
r88553

Is pre-populated with api tokens. Currently editToken and watchToken

var edittoken = mw.user.tokens.get( 'editToken' );
var watchtoken = mw.user.tokens.get( 'watchToken' );

See a live example from the mediawiki.api.watch module.

mediawiki.api[edit | edit source]

This module sets the mw.Api constructor. The main methods of the mw.Api object are get, post, and ajax. The mediawiki.api module (and its plugins) return a promise. This is just like jQuery.ajax (and its derivatives such as jQuery.get, jQuery.post and jQuery.getJSON).

A promise provides three important methods that can be used to register a callback: done(), fail() and always(). In general you should always either have the first two or the latter.

The base mediawiki.api plugin provides two methods that take a raw API query:

There are various plugins (other modules depending on this one) for this module that make it more convenient to use certain API actions actions by abstracting the input and output. The ones in core are listed below.

mw.Api#get[edit | edit source]

var api = new mw.Api();
api.get( {
    action: 'query',
    meta: 'userinfo'
} )
.done( function ( data ) {
        console.log( 'API result:', data );
} )
.fail( function ( error ) {
        console.log( 'API failed :(', error );
} );

mw.Api#post[edit | edit source]

Like api.get, takes a raw API query, but prepares jQuery.ajax internally for a POST request instead.

mw.Api#ajax[edit | edit source]

This is the base method from which all others are derived. Should not be used directly.

mw.Api#errors[edit | edit source]

List of errors that could be received from the API.

mw.Api#warnings[edit | edit source]

List of warnings that could be received from API.

mediawiki.api.category[edit | edit source]

This module depends on mediawiki.api, and extends the mw.Api prototype with methods related to categorization:

mw.Api#isCategory[edit | edit source]

Determines if a category exists.

mw.Api#getCategoriesByPrefix[edit | edit source]

Lists categories with a given prefix.

mw.Api#getCategories[edit | edit source]

Gets the list of categories that a given page belongs to.

mediawiki.api.edit[edit | edit source]

This module depends on mediawiki.api, and extends the mw.Api prototype with methods for editing:

mw.Api#postWithEditToken[edit | edit source]

This posts to the API as specificed by the parameters. It is intended for methods that require an edit token. It will used a cached edit token if one exists, or get one then post.

mw.Api#getEditToken[edit | edit source]

This is a low-level method used by api.postWithEditToken to get tokens.

mw.Api#newSection[edit | edit source]

Creates a new section on the given page, with the given section name and text.

mediawiki.api.parse[edit | edit source]

This module depends on mediawiki.api, and extends the mw.Api prototype with a method for parsing wikitext:

mw.Api#parse[edit | edit source]

Calls the server to parse the given wikitext. Example:

var api = new mw.Api();
 
api.parse( "'''Hello world'''" )
.done( function ( html ) {
        console.log( 'Parsed result:', html );
} );

mediawiki.api.titleblacklist[edit | edit source]

This module depends on mediawiki.api, and extends the mw.Api prototype with a method for checking the title blacklist. It requires TitleBlacklist be installed on the server:

mw.Api#isBlacklisted[edit | edit source]

Determines if a given mw.Title is blacklisted.

mediawiki.api.watch[edit | edit source]

This module depends on mediawiki.api, and extends the mw.Api prototype with methods related to the watchlist:

mw.Api#watch[edit | edit source]

Watches a given title.

mw.Api#unwatch[edit | edit source]

Unwatches a given title.

mediawiki.debug[edit | edit source]

mw.Debug.init[edit | edit source]

Initializes the debugging pane.

mw.Debug.switchPane[edit | edit source]

Switches between debug panes.

mw.Debug.buildHtml[edit | edit source]

Builds HTML for the toolbar.

mw.Debug.buildConsoleTable[edit | edit source]

Builds the console pane.

mw.Debug.buildQueryTable[edit | edit source]

Builds the SQL pane.

mw.Debug.buildDebugLogTable[edit | edit source]

Builds logging pane (legacy).

mw.Debug.buildRequestPane[edit | edit source]

Builds requests pane.

mw.Debug.buildIncludesPane[edit | edit source]

Builds included files pane.

mediawiki.debug.init[edit | edit source]

Calls mw.Debug.init.

mediawiki.feedback[edit | edit source]

User interface for collecting feedback, particularly on new features, using jQuery UI. This sets the mediaWiki.Feedback constructor. Example:

var feedback = new mw.Feedback();
$( '#myButton' ).click( function () { feedback.launch(); } );

mw.Feedback.setup[edit | edit source]

Sets up feedback GUI.

mw.Feedback.display[edit | edit source]

Displays a particular part of the feedback interface.

mw.Feedback.displaySubmitting[edit | edit source]

Shows that the feedback is being added.

mw.Feedback.displayBugs[edit | edit source]

Shows information about bug tracker

mw.Feedback.displayThanks[edit | edit source]

Shows thank you message.

mw.Feedback.displayForm[edit | edit source]

Displays the feedback form, with optional pre-filled contents.

mw.Feedback.displayError[edit | edit source]

Shows given error message.

mw.Feedback.cancel[edit | edit source]

Dismisses feedback form.

mw.Feedback.submit[edit | edit source]

Submits feedback form using mw.Api.newSection.

mw.Feedback.launch[edit | edit source]

Main entry point for displaying the feedback form, with optional pre-filled contents.

mediawiki.jqueryMsg[edit | edit source]

See also Manual:Messages API#Using messages in JavaScript

This module sets the mediawiki.jqueryMsg object. This is used for advanced message parsing. Use it only when mediaWiki.msg and mediaWiki.message do not meet your needs. For example, mediawiki.jqueryMsg is required for plural and gender support, the int: magic word and links.

mediawiki.ui[edit | edit source]

UI module developed as part of the Agora project. It is currently used by the login skin. There is currently one appearance for Vector and another for the rest of the skins. These are some commonly used features:

Buttons[edit | edit source]

All buttons use the mw-ui-button class. The main button for a particular interface (e.g. "Save all changes") should generally also use the mw-ui-primary class. For example:

<input type="submit" name="mw-myextension-submit" value="Save all changes" class="mw-ui-button mw-ui-primary">

It can also be used on other elements:

<span class="mw-ui-button mw-ui-primary">Save all changes</span>

You may also sometimes use the mw-ui-block class, which sets the CSS display property to block and width to 100%. The mw-ui-big class increases the font size of buttons.

Inputs[edit | edit source]

If a form has the mw-ui-vform class, the contents will automatically take on certain styles. For example, text inputs will take on a blue border hue. Checkbox labels should use the mw-ui-checkbox-label class, and surround the actual checkbox.

mediawiki.util[edit | edit source]

addCSS[edit | edit source]

Adds a <style> element to the HEAD and returns the CSSStyleSheet object.

The CSSStyleSheet object can be used to disable the css rules at any later time and re-enable them as well. This can be done through the 'disabled' attribute. When setting this to true, the rules no longer apply. When setting to false, the rules apply again.

See also W3 on CSSStyleSheet for more info.

// Add a simple stylesheet rule
mw.util.addCSS( '.plainlinks { color: green; }' );
 
// Add a rule and set a variable to the sheet
var myCssRules = mw.util.addCSS( '.plainlinks { color: green; }' );
$( '#myButton' ).click( function () {
  // When button is clicked, toggle the stylesheet from true to non-true (false), or from false to non-false (true) 
  myCssRules.disabled = !myCssRules.disabled;
} );

addPortletLink[edit | edit source]

This function is ported from the legacy wikibits keeping it fully backwards compatible, with a few adjustments that support all core skins and with added support for a CSS-selector as nextnode.

Only the first three arguments are required.

// General usage:
mw.util.addPortletLink( portletId, href, text [, id [, tooltip [, accesskey [, nextnode ]]]] );
 
// Add MediaWiki.org-link in the toolbox before the Print-link
mw.util.addPortletLink( 'p-tb', '//www.mediawiki.org/', 'MediaWiki.org',
  't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print' );
 
// The old way of passing a DOM-node still works
mw.util.addPortletLink( 'p-tb', '//www.mediawiki.org/', 'MediaWiki.org',
  't-mworg', 'Go to MediaWiki.org ', 'm', document.getElementById( 't-print' ) );

In case you need to execute a custom function when the user clicks on a portlet, do not use 'javascript:doSomeStuff();' for the href of the portlet. Instead, use the jQuery(...).click to specify the code which should be executed.

// Create portlet link
var portletLink = mw.util.addPortletLink( 'p-cactions', '#',
        'My new portlet link', 'ca-my-portlet', 'Click here to test the new portlet'
);
// Bind click handler
$( portletLink ).click( function ( e ) {
        e.preventDefault();
        // doSomeStuff();
        alert( 'It works!' );
});

$content[edit | edit source]

A jQuery object for a page's overall content area regardless of the skin used. This is, for example, #content in the Vector-skin (before 1.20 it was #bodyContent). This variable is initialized from the mediawiki.page.startup module. Make sure to either add it to your dependencies or wrap it inline in mw.loader.using( 'mediawiki.page.startup', ... );

This does not refer to the area where the page content goes. If you wish to work with that area of the page instead of the overall content area you should use $('#mw-content-text') instead.

/* Add some HTML to the page content */
mw.util.$content.append( '<h2>Lorem ipsum</h2><p>This section was just added to the bottom of the wiki page.</p>' );
 
/* Count number of tables in the page's content with a class of "wikitable" */
var $wikitablesInPage = mw.util.$content.find( 'table.wikitable' );
 
if ( $wikitablesInPage.length ) {
 alert( 'There are ' + $wikitablesInPage.length + ' wikitables on this page.' );
} else {
 alert( 'There are no wikitables on this page.' );
}

Here is a more advanced example involving loading in extra content with an AJAX request. Run this example on a page other than the main page.

/* Loads in main page (or any page for that matter) over AJAX (may be useful for Special:BlankPage) */
 
// Put a loading message on top of the page
mw.util.$content.prepend( '<p><em>Loading...</em></p><hr/>' );
 
// To get the article contents, use #mw-content-text instead.
$('#mw-content-text').load( mw.util.wikiGetlink( mw.config.get( 'wgMainPageTitle' ) ) + ' #mw-content-text', function () {
  mw.notify( 'Load complete!' );
} );

getParamValue[edit | edit source]

This function returns the value of the specified URL parameter. By default it uses the current window's address. Optionally you can pass it a custom location.

It returns null if the parameter is not present. Returns an empty string("") if it was an empty parameter (such as /page.php?some=parameter&emptyparameter=&id=12

// Location: https://www.mediawiki.org/w/index.php?title=ResourceLoader/Default_modules&action=edit&section=28
// Suppose we're editing a page section, this will return the number of the edit section
mw.util.getParamValue( 'section' ); /* returns '28'; */
 
// Extract a value from a custom url
// For example on a diff page where there is:  "← Older edit" and you need the oldid of the previous edit
var oldid = mw.util.getParamValue( 'oldid', '//www.mediawiki.org/w/index.php?title=ResourceLoader/Default_modules&diff=prev&oldid=365296' );
if ( oldid !== null ) {
  alert( 'The previous text version of this page has id: ' + oldid );
} else {
  alert( 'No "oldid" parameter found in the given address.' );
}

isIPv4Address[edit | edit source]

MediaWiki version: = 1.18
r83202

isIPv6Address[edit | edit source]

MediaWiki version: = 1.18
r83202

jsMessage[edit | edit source]

MediaWiki version: = 1.18
r78156

This function is ported from the legacy wikibits keeping it fully backwards compatible, with a few adjustments and with added support to hide the message by calling with no arguments or when passing null.

// Basic usage, replace/add the message on top
mw.util.jsMessage( 'This is something a <strong>message</strong> for the <strong>user</strong>' );
 
// Classed usage, adds/replaces the 'mw-js-message-foobar' as class for the message-box
mw.util.jsMessage( 'Foobar message 01255', 'foobar' );
 
// Any of the folllowing will empty and hide the box
mw.util.jsMessage();
mw.util.jsMessage( '' );
mw.util.jsMessage( null );

rawurlencode[edit | edit source]

This function returns an encoded string in its raw form for use in urls.

var exFooUrl = 'http://example.org/foo/' + mw.util.rawurlencode( mw.config.get( 'wgPageName' ) );

For building query strings, you may want to use jQuery.param instead:

var query = {
 page: 'MyPage',
 value: mw.config.get( 'skin' ),
 action: 'foo'
};
 
var fooQuery = 'http://example.com/stuff.php?' + $.param( query );

validateEmail[edit | edit source]

Returns true if its string parameter is a valid e-mail address according to HTML5 specification, false if not, and null if passed an empty string.

var isValid = mw.util.validateEmail( "joe@example.com" ) === true;

wikiUrlencode[edit | edit source]

This function returns a "pretty" version of a URL encoded wiki page name. It keeps slashes and colons unencoded. The behavior differs from wfUrlencode on the PHP side.

// This url will end up in the user's addressbar, so prettification is useful.
var $histLink = $( '<a>' ).attr(
    'href',
    mw.config.get( 'wgScript' ) + '?action=history&title=' + mw.util.wikiUrlencode( mw.config.get( 'wgPageName' ) ),
);
 
// This will never be shown, don't bother with string concatenation, just encode it regularly with $.param(), much easier.
jQuery.ajax({
    url: mw.config.get( 'wgScript' ) + '?' + $.param({ action: 'history', title: mw.config.get( 'wgPageName' ) }),
    dataType: 'html'
})
.done( function ( html ) {
    /* .. */
});

wikiGetlink[edit | edit source]

This function returns the address to a local wiki page.

var sandboxLink = mw.html.element(
 'a', {
   href: mw.util.wikiGetlink( 'Sandbox 3000' ), // returns "/wiki/Sandbox_3000"
   title: 'Go to Sandbox'
  }, 'Click here to enter the sandbox!'
);

wikiScript[edit | edit source]

MediaWiki version: = 1.18
r88513

This function returns the location of a script on the current wiki. Much like wfScript in GlobalFunctions.php.

Parameters: str - Name of the script (eg. 'api'), defaults to 'index'.

jQuery.getJSON( mw.util.wikiScript( 'api' ), {
  format: 'json',
  action: 'query',
  titles: 'Main Page',
  prop: 'revisions'
} ).done( function ( data ) {
    // data.query
} );

mediawiki.Title[edit | edit source]

This sets the mediaWiki.Title constructor, which has several methods in its prototype. Basic example

var t = new mw.Title( 'Image: foo_bar baz.jpg' );
t.getMain(); // "Foo_bar_baz.jpg"
t.getNamespaceId(); // 6
t.getNamespacePrefix(); // "File:"

mediawiki.Uri[edit | edit source]

Basic examples

var uri = new mw.Uri(); // This throws the following error on 1.19.1: 'Bad constructor arguments'
uri; // Instance for the location of the current window
 
var otheruri = new mw.Uri( 'http://mediawiki.org/' ); // The trailing slash is *required*
otheruri.toString(); // "http://mediawiki.org"

mediawiki.notify[edit | edit source]

Basic examples

mw.notify( 'This is a notification.' ); // Send a plaintext notification
mw.notify( mw.message( 'some-message' ) ); // Use an i18n message to send a notification
mw.notify( $( '<span>This is a <u>HTML</u> notification.</span>' ) ); // Send a html notification with a jQuery instance (a DOM node also works)
 
mw.notify( 'Test', { title: 'Title!' } ); // Give the notification a title
mw.notify( 'Test', { autoHide: false } ); // Don't automatically hide the notification
mw.notify( 'Test', { tag: 'foobar' } ); // Send a notification tagged with a tag
mw.notify( 'Test 2', { tag: 'foobar' } ); // This one will replace the previous 'foobar' notification.

jQuery & plugins[edit | edit source]

jquery[edit | edit source]

More information about jQuery's presence in MediaWiki, see jQuery. For more about jQuery in general and all its core functions, refer to http://api.jquery.com/

jquery.async[edit | edit source]

jquery.autoEllipsis[edit | edit source]

jquery.badge[edit | edit source]

MediaWiki version: = 1.20

This is a jQuery module that allows you to put a red "badge" on an item on the page. 'Badge' in this case should be considered a verb rather than a noun, as the function returns the parent, not the badge itself.

jQuery#badge[edit | edit source]

$element.badge( text );
$element.badge( 5 );
$element.badge( '100+' );
$element.badge( text, inline );
$element.badge( 'New', true );
  • text can be a number or a string. If the value is falsey (0, null, false, '', etc.), any existing badge will be removed.
  • inline determines whether or not to display the badge inline. The default is to overlay the badge over the corner of the parent element. Set this parameter to true to display the badge inline instead.

jquery.checkboxShiftClick[edit | edit source]

jQuery#checkboxShiftClick[edit | edit source]

This single-function plugin can be called to add this functionality to any number of checkboxes. By default (onload) it's applied to all input elements that have a type of checkbox, excluding any with a class of 'noshiftselect'. As it has a built-in prevention to avoid binding the CheckboxShiftClick twice to the same element you can simply run the line below under "Default" again at any time if you want to enable dynamically added checkboxes in the page to be shift-selectable as well. Or alternatively run it on the specific selector of choice (see second example below).

// Default:
$( 'input[type=checkbox]:not(.noshiftselect)' ).checkboxShiftClick();
 
// Enable the functionality for checkboxes in dynamically created form <form id="my-tool-form">
$( 'form#my-tool-form input[type=checkbox]' ).checkboxShiftClick();

jquery.chosen[edit | edit source]

“Chosen is a jQuery plugin that makes long, unwieldy select boxes much more user-friendly.” — harvesthq.github.io

In fact, it turns a select into a combo box with autocomplete functionality by default but also supports grouping, and "tagging" (i.e. multiple values).

$("select").chosen({/* options */});

jquery.client[edit | edit source]

A plugin that extracts information about the client's browser, layout engine and operating system. Use this instead of jQuery.browser, which is deprecated and will be removed from jQuery in the near future.

jQuery.client.profile[edit | edit source]

The profile function is the main function here and returns (and caches) all the information in an object in. All possible values (except for version numbers) are predefined. A typical return looks like this:

/* jQuery.client.profile() */
{
        'name': 'firefox',
        'layout': 'gecko',
        'layoutVersion': '20100101',
        'platform': 'win'
        'version': '10.0.2',
        'versionBase': '10',
        'versionNumber': 10,
}

Here a few examples

if ( $.client.profile().layout == 'gecko' && $.client.profile().platform == 'linux' ) {
 // This will only run on Gecko browsers (ie. Mozilla Firefox) on Linux.
}
 
if ( $.client.profile().name == 'msie' ) {
 // Only for good ol' Internet Explorer
}
 
// Shortcut
var prof = $.client.profile();
if ( prof.name == 'firefox' && prof.versionBase == '2' && prof.platform == 'win' ) {
  // Target Mozilla Firefox 2.x on Windows
}

Check jquery.client.js for possible values of browser names, layout engines and platforms.

jQuery.client.test[edit | edit source]

...

jquery.collapsibleTabs[edit | edit source]

Used by the Vector extension.

jquery.colorUtil[edit | edit source]

MediaWiki version: = 1.18
r79686
getRGB
colors
rgbToHsl
hslToRgb
getColorBrightness

jquery.color[edit | edit source]

MediaWiki version: = 1.17

jquery.cookie[edit | edit source]

This plugin allows you to set, get and delete cookies.

jQuery.cookie[edit | edit source]

// Set cookie (simple, current page/path)
$.cookie( 'myName', 'Flower' );
 
// Set cookie (extra options)
$.cookie( 'myName', 'Flower', {
 expires: 7, // expires in 7 days
 path: '/' // domain-wide, entire wiki
} );
 
// Get cookie
var name = $.cookie( 'myName' );
 
// Delete cookie
$.cookie( 'myName', null );

When deleting a cookie, you must use the same path and domain used when the cookie was set.

Note that when MediaWiki server-side code sets a cookie it usually prefixes it with the database name; this prefix is available to JavaScript code as the mediaWiki.config variable wgCookiePrefix.

Note that users will likely get separate cookies for /wiki/ and /w/ paths in page URLs if you do not specify the extra option { path: '/' } when setting a cookie.

jquery.delayedBind[edit | edit source]

jquery.expandableField[edit | edit source]

jquery.highlightText[edit | edit source]

jquery.json[edit | edit source]

Provides JSON encoding to old browsers which do not support JSON.stringify:

jQuery.toJSON[edit | edit source]

jQuery.evalJSON[edit | edit source]

jQuery.secureEvalJSON[edit | edit source]

var obj = {'a': 1, 'b': 2};
var string = $.toJSON( obj );
 
var jsonString = '{"a":1,"b":2}';
var obj1 = $.evalJSON(jsonString);
var obj2 = $.secureEvalJSON(jsonString);

jquery.jStorage[edit | edit source]

Project home page

var key = "myStorageKey",
    value = $.jStorage.get( key );
 
if ( !$.jStorage.storageAvailable() ) {
    throw new Error( 'No storage available. Fall back to ... or tell the user to install a real browser!' );
}
 
$.jStorage.listenKeyChange( key, function( key, action ) {
    if ( window.console && $.isFunction( console.log ) ) {
        console.log(key + " has been " + action);
    }
} );
 
value = {a: 1, b: 2, c: [3, 4, 5]};
$.jStorage.set( key, value );

jquery.localize[edit | edit source]

MediaWiki version: = 1.17
r77710

Localizes a DOM selection by replacing <html:msg /> elements with localized text and adding localized title and alt attributes to elements with title-msg and alt-msg attributes respectively.

var html = '\
    <p>\
        <html:msg key="title" />\
        <img src="something.jpg" title-msg="title" alt-msg="desc" />\
        <input type="text" placeholder-msg="search" />\
    </p>';
$( 'body' ).append( $( html ).localize() );

jquery.makeCollapsible[edit | edit source]

MediaWiki version: = 1.18
r78914
See also Manual:Collapsible elements.

Makes elements collapsible. It supports lots of variations such as:

Simple
Add "mw-collapsible" to an element (a <div> for example) with some content and save the page. The inner content of this element will be treated as collapsible content. Prepended to the element, before the collapsible content, is a toggle-link with a localized label (collapsible-expand, collapsible-collapse)
Initial state
Adding "mw-collapsed" as additional class will cause the element to be initially collapsed when the page is loaded.
Custom label
HTML5 only Using the data-collapsetext and data-expandtext attributes one can define a custom text for the toggle labels added by the script. When added in wikitext these could populated by a localized message like:
<div class="mw-collapsible" data-expandtext="{{int:show}}" data-collapsetext="{{int:hide}}">
Remote toggle
If you don't want the script to put the default toggle link (whether or not with a custom label) in your element, you can make one of your own. This could reside anywhere inside or outside the collapsible element. It's relationship to the collapsible element is detected by using ID attributes with the prefix mw-customcollapsible and mw-customtoggle for the collapsible element and the togglelink respectively.

Example: Simple collapsible div or table

Input:

{| class="infobox"
! Foo
| Bar
|-
! Lorem
| Ipsum
|-
! More info
|<!--
-->
{| class="wikitable mw-collapsible mw-collapsed" style="width: 100%;"
! Head
! Top
|-
| Cell
| content
|-
| This table is collapsible 
| Because it has the "mw-collapsible" class
|-
| It was initially hidden, because it
| had the "mw-collapsed" class
|}<!--
-->
|-
|}
 
<div class="toccolours mw-collapsible" style="width: 400px;">
This is text is collapsible. {{Lorem}}
</div>

Output:

Foo Bar
Lorem Ipsum
More info
Head Top
Cell content
Abc Zyx
This table is collapsible Because it has the "mw-collapsible" class
It was initially hidden, because it had the "mw-collapsed" class
This is text is collapsible. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.



Example: Hide the collapsible element by default, the toggle element resides outside of it

<div class="mw-customtoggle-myDivision" style="background:#e0e8ff">Click here to toggle the element</div>
 
<div class="mw-collapsible mw-collapsed" id="mw-customcollapsible-myDivision">
<div class="toccolours mw-collapsible-content">Lorem ipsum dolor sit amet...</div>
</div>
 
<div class="mw-customtoggle-myDivision" style="background:#e8ffe0">Clicking will toggle it also!</div>

For other live examples, see Test Wikipedia - Collapsing Testpage.

jquery.placeholder[edit | edit source]

This plugin adds support for placeholder texts in input fields for browsers that don't support the HTML5 attribute yet. If the attribute is not supported it's applied to all input elements with a 'placeholder' attribute, on-load.

It has a built-in check for browser support, but for efficiency it's best to do this check (also) wrapped around to call.

// Default:
if ( !( 'placeholder' in document.createElement( 'input' ) ) ) {
        $( 'input[placeholder]' ).placeholder();
}
 
// Example for your dynamically added foobar fields
$( "form#foobar-ajax input[placeholder]" ).placeholder();

jquery.qunit[edit | edit source]

Testing framework. See http://qunitjs.com.

jquery.qunit.completenessTest[edit | edit source]

CompletenessTest[edit | edit source]

Assesses the completeness (coverage) of test suites for object oriented javascript libraries. Written to be used in environments with jQuery and QUnit.

This is also used by MediaWiki core when running the QUnit test suite with the completenesstest option enabled.

jquery.suggestions[edit | edit source]

There is also jquery.ui.autocomplete.js with similar functionality.

Real world examples: ajaxCategories.js, ext.vector.simpleSearch.js

Example shows suggestions for the summary-line:

function fetchIT(d, y) {
    mw.log( 'fetched' );
    this.suggestions( 'suggestions', ['Lorem ipsum dolor sit amet', 'consectetur adipisici elit', 'sed eiusmod tempor incidunt ut labore et dolore magna aliqua']);
}
 
$( '#wpSummary' ).suggestions( 'fetch', fetchIT );

jquery.tabIndex[edit | edit source]

jquery.tablesorter[edit | edit source]

MediaWiki version: = 1.18
r86088

jquery.textSelection[edit | edit source]

jsMsg( 'The selected text is "' + mw.html.escape( $( '#wpTextbox1' ).textSelection( 'getSelection' ) ) + '".' );

jquery.tipsy[edit | edit source]

Example page; JQuery project page

Option Type Possible values Default Description
gravity string / call-back function 'nw' | 'n' | 'ne' | 'w' | 'e' | 'sw' | 's' | 'se' / $.fn.tipsy.autoNS | $.fn.tipsy.autoWE | pointer or anonymous 'n' sets the positioning of the tooltip relative to the element
fade bool true | false true use fading effect (fadeIn / fadeOut)
title string (an attribute) / call-back function style, class, id, ..., function () { return 'some string'; } title (or if not specified fallback-value; see below) Which string to display as a "tool-tip"?
fallback string 'valid string' used if an element has no tooltip
html bool true | false false interpret the tooltip text as HTML
delayIn number in ms 0, 1, 2, ... 0 How long to wait after onmouseover to show the tip?
delayOut number in ms 0, 1, 2, ... 0 How long to wait after onmouseout to close the tip?
trigger string 'focus' | 'manual' | 'hover' hover When to show the tooltip (useful for forms)
live bool true | false false dynamical add to selectors- see JQuery's live interpretation
offset number in px 0 offset from tooltip to element
opacity number (float) 1.0 opacity of the tooltip
mw.loader.using( 'jquery.tipsy', function () {
    $someObject.prepend(
        $( '<span>', {
            title: 'Some tipsy test title'
        } )
        .append( 'Hover here' )
        .tipsy({
            option: 'value',
            option2: 'value2'
        })
    );
});

jquery.mwExtension[edit | edit source]

MediaWiki version: = 1.17
r76320

There are several methods added to the jQuery object for older browsers serving as backwards-compatibility for new native prototypes in newer browser. Also several other convenience functions have been created such as isEmpty and escapeRE. In MediaWiki 1.17 and 1.18 these methods were part of the "jquery.mwPrototypes" module. In MediaWiki 1.19 this module was renamed to "jquery.mwExtension" (see rev:94227).

jQuery.trimLeft[edit | edit source]

Trims whitespace from the left side of the string

jQuery.trimRight[edit | edit source]

Trims whitespace from the right of the string

jQuery.ucFirst[edit | edit source]

Returns the string with the first character capitalized

jQuery.escapeRE[edit | edit source]

Returns a string for literal use in a regular expressions by escaping characters that have a special meaning in a regex.

jQuery.isDomElement[edit | edit source]

Check whether a passed a variable is a direct link to an element.

jQuery.isEmpty[edit | edit source]

MediaWiki version: = 1.17
r77127

This function checks if a variable is empty. Supports strings, booleans, arrays and objects. The string "0" is considered empty. A string containing only whitespace (ie. " ") is considered not empty.

jQuery.compareArray[edit | edit source]

Compares two arrays and returns a boolean for whether they are in fact the same

jQuery.compareObject[edit | edit source]

MediaWiki version: = 1.17
r78345

Compares two objects for it's properties and values (recursive).

/**
 * Trim
 */
$.trimLeft( '  foo bar  ' ); // "foo bar  ";
$.trimRight( '  foo bar  ' ); // "  foo bar";
$.trim( '  foo bar  ' ); // "foo bar";
 
/**
 * isEmpty
 */
$.isEmpty( 'string' ); // false
$.isEmpty( '0' ); // true
$.isEmpty( '' ); // true
$.isEmpty( [] ); // true
 
 
/**
 * compareArray
 */
$.compareArray( [1, "a", [], [2, 'b'] ], [1, 'a', [], [2, "b"] ] ); // true
$.compareArray( [1, 2], [8, 7] ); // false
 
 
/**
 * isDomElement
 */
// Sure, a plain normal dom element: True
$.isDomElement( document.getElementById( 'content' ) );
 
// This returns an array of dom elements, not a dom element itself: False
$.isDomElement( document.getElementsByClassName( 'portal' ) );
 
// This is a normal dom element: True
$.isDomElement( document.getElementsByClassName( 'portal' )[0] );
 
// jQuery objects are not dom elements: False
$.isDomElement( $( '#content' ) );
 
// jQuery.get(0) returns the raw dom element for the object: True
$.isDomElement( $( '#content' ).get(0) );
 
// Anything else: False
$.isDomElement( 'hello world' );

jQuery UI[edit | edit source]

For more information on and demos for jQuery UI, refer to http://jqueryui.com/

The following components are included:

ResourceLoader
Documentation Features · Vocabulary · Migration guide (users) · Migration guide (developers) · Developing with ResourceLoader · Default modules · Mobile support
Project information Status updates · Version 1 Design Specification (tasks) · Version 2 Design Specification (tasks / tests) · Requirements
Other JavaScript Deprecations