This page lists This section was just added to the bottom of the wiki page. Loading...
some modules that ship with MediaWiki core
by default.
It reflects the current development version of MediaWiki and may vary from the latest stable release.
It does not claim to be as comprehensive and up to date as
Wikimedia's JS documentation on doc.wikimedia.org
, nor does it include every module from the
authoritative list of modules in Resources.php
, but it offers much additional guidance.
For older modules, see the
Migration guide
The modules
jquery
and
mediawiki.base
together form the base environment ("startup") and are always present.
They must not be declared as dependencies.
This is the MediaWiki base module.
It initialises the
mw
global object.
For a list of stable config keys to read from
mw.config
, see
Manual:Interface/JavaScript
// 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.
// Returns a dictionary object containing the variables requested
// as keys and their corresponding values.
const
conf
mw
config
get
'wgServer'
'wgPageName'
'wgCanonicalSpecialPageName'
'wgUserLanguage'
);
if
conf
wgCanonicalSpecialPageName
===
'Blankpage'
// Do stuff...
MediaWiki version:
1.22
r56762
A framework for registering and firing events in JavaScript (as opposed to doing everything on document ready).
For example, the snippet below provides a message once the categories on a page load:
mw
hook
'wikipage.categories'
).
add
$content
=>
if
mw
config
get
'wgCategories'
).
length
===
alert
'Please add categories to this page'
);
);
In user scripts and gadgets you can fire hooks/events prefixed by "userjs.". E.g.:
function
MyScriptInit
()
var
simpleVariable
'done'
var
objectPassed
me
this
};
mw
hook
'userjs.myScript.postInit'
).
fire
simpleVariable
objectPassed
);
//...
Then you subscribe to this event like so:
// here we receive both variables (but we skip them too)
mw
hook
'userjs.myScript.postInit'
).
add
simple
objectPassed
=>
//...
);
hook execution order
edit
Note that hooks are run in a sequence (and in place where they are fired).
function
MyGadget
()
var
objectPassed
abc
'default'
};
this
objectPassed
objectPassed
console
log
'before hooks'
objectPassed
);
// (2)
mw
hook
'userjs.MyGadget.postInit'
).
fire
objectPassed
);
console
log
'after hooks'
objectPassed
);
// (4)
mw
hook
'userjs.MyGadget.postInit'
).
add
objectPassed
=>
objectPassed
abc
'changed in hook'
console
log
'inside a hook'
objectPassed
);
// (3)
);
console
log
'before init'
);
// (1)
const
gadget
new
MyGadget
();
console
log
'after init'
gadget
objectPassed
);
// (5)
Above will result in following order:
before init
before hooks, Object { abc: "default" }
inside a hook, Object { abc: "changed in hook" }
after hooks, Object { abc: "changed in hook" }
after init, Object { abc: "changed in hook" }
Helper functions for escaping and creating strings of HTML.
MediaWiki version:
1.32
Shortcut for
mw.inspect.runReports
Shows in the console a list of all ResourceLoader modules that are loaded on this page, sorted by the total size of each module's JavaScript, CSS, etc.
Collection of methods to help log messages to the console.
If the
mediawiki.jqueryMsg
module is loaded, the behaviour of this module changes significantly.
See above link.
Get the current time, measured in milliseconds since January 1, 1970 (UTC).
On browsers that implement the
Navigation Timing API
, this function will produce floating-point values with microsecond precision that are guaranteed to be monotonic.
On all other browsers, it will fall back to using
Date
var
totalTime
time
mw
now
();
// some expensive code
totalTime
mw
now
()
time
Publish arbitrary data into a buffer for later consumption.
The design of
mw.track()
encourages async and dependency-free interactions through a stable message contract, based on only topic string, and some data.
MediaWiki JavaScript code can call
mw.track()
to performantly capture and observe data from anywhere.
There is a complete separation of concerns between publisher and subscriber.
You do not need to know the name of the extension consuming the data, or to depend on its module, or to load it first, or even call its code in order for the data to be processed.
Instead, if and when that other feature loads its module, it will call
mw.trackSubscribe()
to access the buffer and process it from that point.
Topic names consist of dot-separated path components, arranged from most general to most specific.
Each path component should have a clear and well-defined purpose.
Data handlers are registered via
mw.trackSubscribe()
, and receive the full set of events that match their subscription, including those that fired before the handler was bound.
Notable example is
Extension:EventLogging
mw
track
'event.Sandbox'
name
'grain'
number
12
);
// ... if the optional EventLogging extension is installed and enabled,
// ... and after "ext.eventLogging" module has finished loading,
// ... it will call `mw.trackSubscribe( 'event.' )`
// ... and eventually call `mw.eventLog.logEvent()` for each event.
Notable example is
statsd.js
in the
Extension:WikimediaEvents
source
):
// Prometheus counter
mw
track
'stats.mediawiki_foo_bar_total'
);
// defaults to increment=1
// note field values should not contain "-" character as these will be looked as invalid values.
mw
track
'stats.mediawiki_foo_bar_total'
something
'example'
skin
mw
config
get
'skin'
).
replace
/-/g
''
);
// Prometheus timer
mw
track
'stats.mediawiki_foo_quux_seconds'
42.3
);
// 42ms
// Prometheus histogram
// _distribution suffix is required, also the buckets label must be there.
// The buckets must be added as hard-coded values, not dynamically calculated,
// because they must not be changed once data collection has started
mw
track
'stats.mediawiki_foo_bar_distribution'
0.347
wiki
mw
config
get
'wgDBname'
),
buckets
0.05
0.1
0.2
0.3
0.5
0.8
1.1
1.5
],
// choose these as it makes sense for you!
},
);
// ... if WikimediaEvents is installed, then this
// ... eventually sends a beacon to the StatsV service
statsd.js checks that Prometheus metrics have the correct prefix ("mediawiki_") and suffix ("_total" or "_seconds"). Without these, warnings will be logged or errors will be thrown.
To use stat counters in gadgets, refer to
Gadget kitchen: recording metrics
To learn how StatsV works, refer to
Statsv
on Wikitech.
Graphite
has been sunset
but previously events could be fired with the following code.
These examples are kept for reference, but WILL NOT WORK IN PRODUCTION.
// Graphite counter
mw
track
'counter.MediaWiki.foo.bar.example'
);
// Graphite timer
mw
track
'timer.MediaWiki.foo.quux'
42.3
);
// 42ms
Creates
Bubble notifications
. 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
'This is an HTML notification.'
);
// Send an 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.
For available options, see
Bubble notifications § API
Load one or more modules, a script or a stylesheet.
To load an external script or stylesheet, the URL must start with either "
", "
" or "
//
" (protocol-relative), or "
" (local path).
Provide a MIME-type as second parameter (either "
text/javascript
" or "
text/css
").
If no MIME-type is provided, the default "
text/javascript
" is assumed.
mw.loader
creates an asynchronous request, if you need to run code that depends on a module, use mw.loader.using instead (which provides a callback).
If you need a callback from an external script, use
mw.loader.getScript
(or
jQuery.getScript
).
Loader instructions represent the intent that a module by that name should be loaded.
It will not load the same module a second time if it has already been loaded previously.
This does not apply to scripts and stylesheets – they
will
be loaded each time, even if loaded previously.
If a script defines
window.Foo
, you can use
( window.Foo !== undefined )
to check if that script has already been loaded.
// Module by name
mw
loader
load
'oojs'
);
// Multiple modules
mw
loader
load
'oojs'
'mediawiki.Title'
);
// Local gadget module. These must be defined in [[MediaWiki:Gadgets-definition]].
mw
loader
load
'ext.gadget.Navigation_popups'
);
// JavaScript page
mw
loader
load
'https://www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript'
);
mw
loader
load
'https://commons.wikimedia.org/w/index.php?title=MediaWiki:Gadget-HotCat.js&action=raw&ctype=text/javascript'
);
// CSS stylesheet
mw
loader
load
'https://en.wikipedia.org/w/index.php?title=User:Example/custom-foo.css&action=raw&ctype=text/css'
'text/css'
);
// CSS stylesheet from wiki page using getUrl method
mw
loader
load
mw
util
getUrl
'MediaWiki:Foo.css'
action
'raw'
'&ctype=text/css'
'text/css'
);
// External stylesheet
mw
loader
load
'https://wiki.example/mystyles.css'
'text/css'
);
Load one or more modules, and execute a function once those modules are loaded.
See
JS Documentation
Since MediaWiki 1.28 the promise returned by this function is resolved with a
require
function, which can be used to access the public interface of
package modules
For example:
mw
loader
using
'mediawiki.util'
],
require
=>
const
util
require
'mediawiki.util'
);
);
mw.loader.getScript
edit
Load a script by URL.
Returns a jQuery
promise object
which can be used to specify callbacks.
Example:
mw
loader
getScript
'https://example.org/x-1.0.0.js'
).
then
()
=>
// Script succeeded. You can use X now.
},
=>
// Script failed. X is not available
mw
log
error
message
);
// => "Failed to load script"
);
To get a single callback from multiple promises, use
jQuery.when
or Promise.all
when
mw
loader
getScript
'https://example.org/x-1.0.0.js'
),
mw
loader
getScript
'https://example.org/y-2.0.0.js'
).
then
()
=>
// Both script succeeded. You can use X and Y now.
},
=>
// A script failed, and is not available
mw
log
error
message
);
// => "Failed to load script"
);
MediaWiki version:
1.17
Import a local JavaScript page from the User or MediaWiki namespace, for use by
user scripts
and site-wide scripts.
If the same title is imported multiple times, it will only be loaded and executed once.
MediaWiki version:
1.17
Import a local CSS page from the User or MediaWiki namespace, for use by
user scripts
and site-wide scripts.
Stub for logging Javascript errors; always loaded.
Provides a method for logging caught exceptions:
try
// ...
catch
mw
errorLogger
logError
'my-component'
);
Sends two kinds of
#mw.track
events:
error_caught
: this is where errors logged via
logError
go
global_error
: uncaught exceptions reported by the browser
By default nothing is done with these events; an
mw.trackSubscribe
handler can forward them to the appropriate logging API. See e.g.
clientError.js
in
Extension:WikimediaEvents
Module that represents information about the current user.
mw.user.clientPrefs
edit
Available since
1.41.0-wmf.20
Can be used to manipulate certain classes on the HTML element such that they do not result in a flash of unstyled content.
This can be utilized where you need to make render blocking changes for anonymous users.
By design the only classes that can be manipulated are classes with the suffix
-clientpref-[A-Za-z0-9]
This is to prevent unintended manipulation of classes as well as serving as an indicator to people viewing the HTML source of what classes are subject to manipulation.
// Returns the current value of the client preference "foo".
// The value of preference corresponds with a class on the HTML element that matches the
// form foo-clientpref-
// For example if there is a class on the HTML element foo-clientpref-1 then get will return 1.
// returns false if there is no class on the HTML element e.g. nothing matches the regular
// expression /foo-clientpref-[a-zA-Z0-9]+/
mw
user
clientPrefs
get
'foo'
);
// Returns false if no class was found on the HTML element.
// If there is a class foo-clientpref-1 on the HTML element this will be replaced with
// foo-clientpref-5.
// Importantly: This replacement will persist across page views.
mw
user
clientPrefs
set
'foo'
'5'
);
Contains
the preferences of the user
, or the defaults when logged out.
// Get a preference option and use it directly
alert
'According to your preferences, your gender is '
mw
user
options
get
'gender'
);
// Get several preferences and compare them
const
opts
mw
user
options
get
'diffonly'
'showhiddencats'
);
if
opts
diffonly
===
&&
opts
showhiddencats
===
false
// User's preferences match
else
// User's preferences don't match
This module is loaded asynchronously and may depend on a separate HTTP request for the
user.defaults
module.
Always declare the relevant dependencies for your module, or use
mw.loader.using()
Example of using options in gadgets as permanent preferences.
See also:
mw.Api#saveOptions
var
MwGadgetUserOptions
class
/** The key should be: "userjs--unique-gadget-name--option". */
constructor
saveKey
this
saveKey
saveKey
this
api
new
mw
Api
();
/** Save to MediaWiki user-store (async compatible). */
options
const
data
{};
data
this
saveKey
JSON
stringify
options
);
return
this
api
saveOptions
data
);
/** Read from MediaWiki user-store (synchronous). */
read
()
const
raw
mw
user
options
get
this
saveKey
);
try
return
raw
JSON
parse
raw
null
catch
console
warn
'Failed to parse saved options'
);
return
null
};
// Example usage with await
async
()
=>
let
optionsHelper
new
MwGadgetUserOptions
'userjs-tmp1'
);
// this will read options available on load, this is fast
let
options
optionsHelper
read
();
console
log
`User's options:`
options
);
options
'abc'
'def'
true
};
await
optionsHelper
options
);
// you don't need to a-wait, but you can
console
log
`Saved new options`
);
})();
MediaWiki version:
1.19
r88553
This contains an
mw.Map
object, pre-populated with tokens for use by
mediawiki.api
This module provides the
mw.Api
and
mw.Rest
objects.
The main methods of the
mw.Api
object are:
get()
post()
ajax()
The
mediawiki.api
[
Promise
– similar to
jQuery.ajax
jQuery.get
jQuery.post
jQuery.getJSON
Before MediaWiki 1.32
Gerrit change 434179
, the methods were part of separate modules named under
mediawiki.api.*
These have been merged into the main module
mediawiki.api
, so you only have to depend on that module.
The submodules have been deprecated with warnings.
These submodules have been removed in MediaWiki 1.33.
Examples of methods that are available:
mw.Api#edit
- Edit an existing page.
mw.Api#saveOptions
- Changes one or more user preferences.
mw.Api#watch
- Add a given title (or titles) to the user's
watchlist
// Example
const
api
new
mw
Api
();
api
watch
'Page to watch'
);
Cookie module that uses the same settings as the MediaWiki server-side configuration (except for
wgCookieSecure
).
Usage example:
mw
set
'myCookie'
'some-value'
);
const
value
mw
get
'myCookie'
);
This module prepends the cookie names with
$wgCookiePrefix
(e.g. "
enwiki
myCookie=some-value").
Avoid accessing the same cookie in different ways, for example via
mw.cookie
and via
$.cookie
, because you may encounter issues if doing so.
See the API documentation for available options.
MediaWiki version:
1.19
User interface for collecting feedback, particularly on new features.
MediaWiki version:
1.26
An extension of
mediawiki.api
specifially geared toward handling everything required to communicate with another MediaWiki wiki via cross-origin requests (CORS). See
Manual:CORS
MediaWiki version:
1.36
Extension of mw.Rest. See
Manual:CORS
Extension of mw.Upload.
This module upgrades the
mw.message
parser to support basic wikitext localisation and formatting features. For example,
mediawiki.jqueryMsg
is required for
plural and gender support
, the
int: magic word
and links.
Register and match a set of in-page navigation routes (i.e. hash fragments). It is based on
OOjs
Wrapper for HTML5 Web Storage (localStorage, and sessionStorage).
If you are migrating from
$.jStorage
, note that
mw.storage.get()
and
mw.storage.set()
only store string values. Use
JSON.stringify()
and
JSON.parse()
or
parseInt
parseFloat
accordingly when setting and getting non-string values. You may also use
mw.storage.getObject()
and
mw.storage.setObject()
Gerrit change 506145
) so that MediaWiki transparently interleaves a JSON serialization.
MediaWiki version:
1.22
(deprecated in 1.29)
Use
Codex
instead!
User-interface module developed as part of the
Agora
project. It defines
mw-ui-*
CSS styles. It was used in the
and
Create account
forms and in several extensions and its different modules have been deprecated since v1.29 onwards, replaced by components of Wikimedia Design System Codex.
Module providing MediaWiki-specific OOUI widgets like user input widget or namespace input widget.
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
const
myCssRules
mw
util
addCSS
'.plainlinks { color: green; }'
);
'#myButton'
).
on
'click'
()
=>
// When button is clicked, toggle the stylesheet from true to non-true (false), or from false to non-false (true)
myCssRules
disabled
myCssRules
disabled
);
This function allows you to create a new portlet in the page.
Only the first argument is required which is the ID of the new portlet. When only using the first argument, no portlet will be added to the page and you must insert it yourself using the return value. When only specifying the first value, you must append the portlet before using the mw.util.addPortletLink API.
const
mw
util
addPortlet
'detached'
);
document
body
appendChild
);
mw
util
addPortletLink
'detached'
'#'
'My test link'
);
The second argument allows you to create a label - which is important for menus that appear in the sidebar or as dropdowns.
The third parameter when used will automatically append the portlet to the page
before
the provoided selector. It also provides a hint to skins which will make the new portlet mimic the styling of that portlet.
See the
mw.util JS documentation
for more details.
// create a portlet that is appended before #p-interaction and mimics the styling of #p-interaction.
mw
util
addPortlet
'p-mytest'
'My test portlet'
'#p-interaction'
);
mw
util
addPortletLink
'p-mytest'
'#'
'My test link'
);
For many use cases, the menu may not appear styled as expected and the portlet is provided as is. In these situations you should provide your own styling.
Appending portlets in different locations
edit
Sometimes you will want to use the third parameter to mimic the styling of the portlet, but not to append
before.
To do this you must use the return value, and relocate it to another location.
const
mw
util
addPortlet
'p-mytest'
'My test portlet'
'#p-interaction'
);
mw
util
addPortletLink
'p-mytest'
'#'
'My test link'
);
// move portlet to end of list.
if
parentNode
appendChild
);
Dropdowns (Vector-only)
edit
The Vector (2022) and Vector legacy (2010) skins support adding portlets as dropdown menus in the tab bar. This is implemented by trapping requests to create a portlet with the selector
#p-cactions
in the
before
argument and mimicking the style the skin uses for its own dropdown menus.
// create a dropdown menu in Vector legacy and Vector
mw
util
addPortlet
'p-mytest'
'My test dropdown'
'#p-cactions'
);
mw
util
addPortletLink
'p-mytest'
'#'
'My test link'
);
In Monobook this will instead create a regular portlet in the left sidebar. In Timeless it will create one in the right sidebar. In skins where the element #p-cactions doesn't exist (for example Minerva on mobile for anonymous users) it is essentially a NOOP. Note, skins are not required to support this function (for example Minerva as a desktop skin) so please test thoroughly across different skins and guard your code accordingly.
Appending this portlet and moving it to mimick the dropdown style works in Vector legacy (2010), but will not work in Vector (2022) because the skin wraps it in additional markup (your portlet exists inside a dropdown menu the skin created for you, but it is not itself a dropdown menu). So in order to move it elsewhere, for example to get a dropdown next to the main page tabs on the left, you will have to find the DOM node representing the actual dropdown and move that. This is not recommended because it relies on the skin's internal implementation (markup structure and styling) so it
will
break when the implementation changes, but if you need this you can currently do something like this:
// create a dropdown menu in Vector legacy and Vector
const
mw
util
addPortlet
'p-mytest'
'My test dropdown'
'#p-cactions'
);
mw
util
addPortletLink
'p-mytest'
'#'
'My test link'
);
if
mw
config
get
"skin"
===
'vector-2022'
// rely on Vector using the ID you provided for the portlet and
// appending "-dropdown" to it as the ID for the actual dropdown.
'#p-mytest'
'-dropdown'
).
appendTo
'#left-navigation'
);
else
// use the node returned by mw.util.addPortlet()
).
appendTo
'#left-navigation'
);
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
. Note that it doesn't support MobileFrontend with the Minerva skin for logged-out users.
Only the first three arguments are required. In case you need to execute a custom function when the user clicks on a portlet, use the
jQuery(...).on('click', .. )
on returned Element object to attach a callback that runs the code that should be executed.
See the
mw.util documentation
for details.
// First wait for mediawiki.util to load, and the page to be ready.
when
mw
loader
using
'mediawiki.util'
),
ready
).
then
()
=>
// General usage pattern:
// mw.util.addPortletLink( portletId, href, text /* Optional: , id, tooltip, accesskey, nextnode */ );
// Example: Add a link to mediawiki.org to the Tools area, above the "Special pages" link.
const
newElement
mw
util
addPortletLink
'p-tb'
'https://www.mediawiki.org/'
'Link to mediawiki.org'
't-mworg'
'Go to www.mediawiki.org'
'm'
'#t-specialpages'
);
// The old way of passing a DOM-node also works
mw
util
addPortletLink
'p-tb'
'https://www.mediawiki.org/'
'Link to mediawiki.org'
't-mworg'
'Go to www.mediawiki.org'
'm'
document
getElementById
't-specialpages'
);
);
Note about icons: The id will be used to construct an icon class in certain skins (for example mw-ui-icon-vector-gadget-cx-language in Vector). Callers are expected to add their own CSS in addition to calling addPortletLink if needed.
This function allows you to hide a portlet (menu) consistently across skins.
// First wait for mediawiki.util to load, and the page to be ready.
when
mw
loader
using
'mediawiki.util'
),
ready
).
then
()
=>
/// hide toolbox
mw
util
hidePortlet
'p-tb'
);
);
// First wait for mediawiki.util to load, and the page to be ready.
when
mw
loader
using
'mediawiki.util'
),
ready
).
then
()
=>
mw
util
addSubtitle
'Hello'
);
const
sub
document
createElement
'div'
);
sub
textContent
' world'
mw
util
addSubtitle
sub
);
);
Usually called alongside addSubtitle when you want to refresh the subtitle contents. Given you can only add to the subtitle, you must clear its existing contents if you want to redraw.
// First wait for mediawiki.util to load, and the page to be ready.
when
mw
loader
using
'mediawiki.util'
),
ready
).
then
()
=>
mw
util
clearSubtitle
();
);
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 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.
This property is populated on document ready. To use it, wait for
$.ready
and be sure to have a module dependency on
mediawiki.util
which will ensure your document ready handler fires after initialization.
Because of the lazy-initialised nature of this property, you are discouraged from using it.
/* Add some HTML to the page content */
mw
util
$content
append
'Lorem ipsum
);
/* Count number of tables in the page's content with a class of "wikitable" */
const
$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
'
'
);
// To get the article contents, use #mw-content-text instead.
'#mw-content-text'
).
load
mw
util
getUrl
''
' #mw-content-text'
function
()
mw
notify
'Load complete!'
);
);
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
// Suppose we're viewing and old revision
// at https://www.example.org/w/index.php?title=Hello_world&oldid=123
var
oldid
mw
util
getParamValue
'section'
);
// ^ '123'
// If we get the value from ``, e.g. an "← Older edit" link
var
oldid
mw
util
getParamValue
'oldid'
'https://www.example.org/w/index.php?title=Hello_world&oldid=500'
);
// ^ '500'
MediaWiki version:
1.18
r83202
This function returns bool for passed string is valid IPv4 Address or not.
// true
mw
util
isIPv4Address
'192.0.2.0'
);
// false (range is invalid IPv4 Address)
mw
util
isIPv4Address
'192.0.2.0/24'
);
// false
mw
util
isIPv4Address
'string'
);
MediaWiki version:
1.43
r83202
This function allows you to render an error or warning message. This method should only be called in environments where Codex styles have been loaded (for example mediawiki.codex.messagebox.styles module)
document
body
appendChild
mw
util
messageBox
'Error occurred'
'error'
);
document
body
appendChild
mw
util
messageBox
'Warning occurred'
'warning'
);
document
body
appendChild
mw
util
messageBox
'Notice about something.,'
'notice'
);
MediaWiki version:
1.18
r83202
This function returns bool for passed string is valid IPv6 Address or not.
// true
mw
util
isIPv6Address
'2001:db8:a:0:0:0:0:0'
);
// true
mw
util
isIPv6Address
'2001:db8:a::'
);
// false (range is invalid IPv6 Address)
mw
util
isIPv6Address
'2001:db8:a::/32'
);
// false
mw
util
isIPv6Address
'string'
);
This function returns an encoded string in its raw form for use in urls.
const
exFooUrl
'http://example.org/foo/'
mw
util
rawurlencode
mw
config
get
'wgPageName'
);
For building query strings, you may want to use
jQuery.param
instead:
const
query
page
'MyPage'
value
mw
config
get
'skin'
),
action
'foo'
};
const
fooQuery
'http://example.com/stuff.php?'
param
query
);
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 (e.g. '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 versions:
1.26 – 1.35
(deprecated in 1.34)
See
ResourceLoader/Migration guide § mediawiki.RegExp
This sets the
mw.Title
constructor, which has several methods in its prototype. Basic example:
const
new
mw
Title
'Image: foo_bar baz.jpg'
);
getMain
();
// "Foo_bar_baz.jpg"
getNamespaceId
();
// 6
getNamespacePrefix
();
// "File:"
(deprecated in 1.43)
Use browser's
native URL interface
instead.
Moment.js can parse, manipulate, and format date-time timestamps. Localisation is automatically loaded and configured for the current user interface language.
const
moment
require
'moment'
);
moment
'2011-04-01 09:00'
).
format
'LLLL'
);
// "Friday, 1 April 2011 9:00 AM"
moment
version
//> "2.25.2"
MediaWiki version:
1.23
OOjs
is a libary that provides a consistent way of implementing object-oriented design in JS.
MediaWiki version:
1.23
OOUI
is a user interface toolkit based on OOjs. Note that
oojs-ui
is just a legacy name for the module. See all the known
OOUI module names
More information about jQuery's presence in MediaWiki, see
jQuery
. For more about jQuery in general and all its core functions, refer to
ResourceLoader provides jQuery as part of its
base environment
(the loader client uses jQuery internally), therefore this module is
always
loaded and should not (and in fact can not) be loaded through ResourceLoader (as dependency or otherwise).
“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 */
);
A plugin that extracts information about the client's browser, layout engine, and operating system.
jQuery.client.profile
edit
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
const
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.
MediaWiki versions:
1.17 – 1.40
This module was removed in
MediaWiki 1.41
via
Gerrit change 964085
MediaWiki version:
1.41
(deprecated in 1.41)
To use jQuery cookie methods, load the
mediawiki.cookie
module. It is recommended that you use
mw.cookie
interface as it automatically applies appropiate settings based onMediaWiki site configuration (such as domain, path, and retention).
This plugin allows you to set, get and delete cookies.
// Set cookie (simple, current page/path)
'myName'
'Flower'
);
// Set cookie (extra options)
'myName'
'Flower'
expires
// expires in 7 days
path
'/'
// domain-wide, entire wiki
);
// Get cookie
const
name
'myName'
);
// Delete cookie
// Deprecated since 1.2 please use $.removeCookie( 'foo' ) instead
'myName'
null
);
removeCookie
'foo'
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
mw.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.
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
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 be 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. Its relationship to the collapsible element is detected by using an ID attribute with the prefix
mw-customcollapsible
and a corresponding class attribute with prefix
mw-customtoggle
for the collapsible element and the togglelink respectively.
Example: Simple collapsible div or table
Input:
{| class="wikitable"
! 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
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
Input:
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
Output:
Click here to toggle the element
Lorem ipsum dolor sit amet...
Clicking will toggle it also!
For other live examples, see
Test Wikipedia - Collapsing Testpage
MediaWiki versions:
1.18 – 1.35
r86088
(deprecated in 1.34)
MediaWiki version:
1.18
r86088
mw
util
jsMessage
'The selected text is "'
mw
html
escape
'#wpTextbox1'
).
textSelection
'getSelection'
'".'
);
(deprecated in 1.28)
The library will be available for the forseeable future, but overlaps with functionality within
OOUI
and provides a suboptimal experience to mobile users.
Where jQuery.tipsy is being used, we encourage developers to inspect OOUI and feedback on how the library might be improved to support the usecase that jquery.tipsy provides.
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, ...
How long to wait after onmouseover to show the tip?
delayOut
number in ms
0, 1, 2, ...
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
offset from tooltip to element
opacity
number (float)
1.0
opacity of the tooltip
mw
loader
using
'jquery.tipsy'
()
=>
$someObject
prepend
''
title
'Some tipsy test title'
append
'Hover here'
tipsy
option
'value'
option2
'value2'
);
);
(deprecated in 1.29)
Please use
Codex
instead.
For more information on and demos for jQuery UI, refer to
This module loads site scripts from the pages:
MediaWiki:Common.js
and
MediaWiki:Vector.js
(depending on the current skin).
If
$wgUseSiteJs
is disabled by configuration, then the module is empty.
This module loads:
User:
User:
(depending on current skin),
MediaWiki:Group-user.js
MediaWiki:Group-
(for each group the current user is a member of, e.g. "sysop", "bureaucrat" etc.)
If
$wgAllowUserJs
is disabled by configuration, then the "User" sub pages are not included.
If
$wgUseSiteJs
is disabled by configuration, then the "MediaWiki:Group-" pages are not included.
US