mediawiki.util

Utility library provided by the mediawiki.util ResourceLoader module. Accessible inside ResourceLoader modules or for gadgets as part of the mw global object.

Example

// Inside MediaWiki extensions
const util = require( 'mediawiki.util' );
// In gadgets
const mwUtil = mw.util;

Properties

$content :jQuerystatic #

The content wrapper of the skin (.mw-body, for example).

Populated on document ready. To use this property, 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're discouraged from using it.

If you need just the wikipage content (not any of the extra elements output by the skin), use $( '#mw-content-text' ) instead. Or listen to wikipage.content which will allow your code to re-run when the page changes (e.g. live preview or re-render after ajax save).

Type:

Source:
The content wrapper of the skin (.mw-body, for example).

Methods

addCSS(text) → {CSSStyleSheet}static #

Append a new style block to the head and return the CSSStyleSheet object.

To access the <style> element, reference sheet.ownerNode, or call the mw.loader.addStyleTag method directly.

This function returns the CSSStyleSheet object for convenience with features that are managed at that level, such as toggling of styles:

var sheet = util.addCSS( '.foobar { display: none; }' );
$( '#myButton' ).click( function () {
    // Toggle the sheet on and off
    sheet.disabled = !sheet.disabled;
} );

See also MDN: CSSStyleSheet.

Parameters:

Name Type Description
text string

CSS to be appended

Source:

Returns:

The sheet object

Type
CSSStyleSheet
Append a new style block to the head and return the CSSStyleSheet object.

addPortlet(id, label, before) → {HTMLElement|null}static #

Creates a detached portlet Element in the skin with no elements.

Parameters:

Name Type Attributes Description
id string

of the new portlet.

label string optional

of the new portlet.

before string optional

selector of the element preceding the new portlet. If not passed the caller is responsible for appending the element to the DOM before using addPortletLink.

Source:

Fires:

Returns:

will be null if it was not possible to create an portlet with the required information e.g. the selector given in before parameter could not be resolved to an existing element in the page.

Type
HTMLElement | null
Creates a detached portlet Element in the skin with no elements.
Add a link to a portlet menu on the page.

addSubtitle(nodeOrHTMLString)static #

Add content to the subtitle of the skin.

Parameters:

Name Type Description
nodeOrHTMLString HTMLElement | string
Source:
Add content to the subtitle of the skin.

clearSubtitle()static #

Clears the entire subtitle if present in the page. Used for refreshing subtitle after edit with response from parse API.

Source:
Clears the entire subtitle if present in the page.

debounce(func, wait, immediate) → {function}static #

Return a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If immediate is passed, trigger the function on the leading edge, instead of the trailing.

Ported from Underscore.js 1.5.2, Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors, distributed under the MIT license, from https://github.com/jashkenas/underscore/blob/1.5.2/underscore.js#L689.

Parameters:

Name Type Attributes Default Description
func function

Function to debounce

wait number optional
0

Wait period in milliseconds

immediate boolean optional

Trigger on leading edge

Since:
  • 1.34
Source:

Returns:

Debounced function

Type
function

Return a function, that, as long as it continues to be invoked, will not be triggered.

escapeIdForAttribute(str) → {string}static #

Encode a string as CSS id, for use as HTML id attribute value.

Analog to Sanitizer::escapeIdForAttribute() in PHP.

Parameters:

Name Type Description
str string

String to encode

Since:
  • 1.30
Source:

Returns:

Encoded string

Type
string
Encode a string as CSS id, for use as HTML id attribute value.
Encode a string as URL fragment, for use as HTML anchor link.

escapeRegExp(str) → {string}static #

Escape string for safe inclusion in regular expression.

The following characters are escaped:

\ { } ( ) | . ? * + - ^ $ [ ]

Parameters:

Name Type Description
str string

String to escape

Since:
  • 1.26; moved to mw.util in 1.34
Source:

Returns:

Escaped string

Type
string
Escape string for safe inclusion in regular expression.

getArrayParam(param, params) → {Array.<string>|null}static #

Get the value for an array query parameter, combined according to similar rules as PHP uses. Currently this does not handle associative or multi-dimensional arrays, but that may be improved in the future.

Example

mw.util.getArrayParam( 'foo', new URLSearchParams( '?foo[0]=a&foo[1]=b' ) ); // [ 'a', 'b' ]
mw.util.getArrayParam( 'foo', new URLSearchParams( '?foo[]=a&foo[]=b' ) ); // [ 'a', 'b' ]
mw.util.getArrayParam( 'foo', new URLSearchParams( '?foo=a' ) ); // null

Parameters:

Name Type Attributes Description
param string

The parameter name.

params URLSearchParams optional

Parsed URL parameters to search through, defaulting to the current browsing location.

Source:

Returns:

Parameter value, or null if parameter was not found.

Type
Array.<string> | null
Get the value for an array query parameter, combined according to similar rules as PHP uses.

getParamValue(param, url) → {string|null}static #

Get the value for a given URL query parameter.

Example

mw.util.getParamValue( 'foo', '/?foo=x' ); // "x"
mw.util.getParamValue( 'foo', '/?foo=' ); // ""
mw.util.getParamValue( 'foo', '/' ); // null

Parameters:

Name Type Attributes Default Description
param string

The parameter name.

url string optional
location.href

URL to search through, defaulting to the current browsing location.

Source:

Returns:

Parameter value, or null if parameter was not found.

Type
string | null
Get the value for a given URL query parameter.

getTargetFromFragment(hash) → {HTMLElement|null}static #

Get the target element from a link hash.

This is the same element as you would get from document.querySelectorAll(':target'), but can be used on an arbitrary hash fragment, or after pushState/replaceState has been used.

Link fragments can be unencoded, fully encoded or partially encoded, as defined in the spec.

We can't just use decodeURI as that assumes the fragment is fully encoded, and throws an error on a string like '%A', so we use the percent-decode.

Parameters:

Name Type Attributes Description
hash string optional

Hash fragment, without the leading '#'. Taken from location.hash if omitted.

Source:

Returns:

Element, if found

Type
HTMLElement | null
Get the target element from a link hash.

getUrl(pageName, params) → {string}static #

Get the URL to a given local wiki page name.

Parameters:

Name Type Attributes Default Description
pageName string | null optional
wgPageName

Page name

params Object optional

A mapping of query parameter names to values, e.g. { action: 'edit' }

Source:

Returns:

URL, relative to wgServer.

Type
string
Get the URL to a given local wiki page name.

hidePortlet(portletId)static #

Hide a portlet.

Parameters:

Name Type Description
portletId string

ID of the target portlet (e.g. 'p-cactions' or 'p-personal')

Source:
Hide a portlet.

isIPAddress(address, allowBlock) → {boolean}static #

Check whether a string is a valid IP address.

Parameters:

Name Type Attributes Default Description
address string

String to check

allowBlock boolean optional
false

If a block of IPs should be allowed

Since:
  • 1.25
Source:

Returns:

Type
boolean
Check whether a string is a valid IP address.

isIPv4Address(address, allowBlock) → {boolean}static #

Whether a string is a valid IPv4 address or not.

Based on \Wikimedia\IPUtils::isIPv4 in PHP.

Example

// Valid
mw.util.isIPv4Address( '80.100.20.101' );
mw.util.isIPv4Address( '192.168.1.101' );

// Invalid
mw.util.isIPv4Address( '192.0.2.0/24' );
mw.util.isIPv4Address( 'hello' );

Parameters:

Name Type Attributes Default Description
address string
allowBlock boolean optional
false
Source:

Returns:

Type
boolean
Whether a string is a valid IPv4 address or not.

isIPv6Address(address, allowBlock) → {boolean}static #

Whether a string is a valid IPv6 address or not.

Based on \Wikimedia\IPUtils::isIPv6 in PHP.

Example

// Valid
mw.util.isIPv6Address( '2001:db8:a:0:0:0:0:0' );
mw.util.isIPv6Address( '2001:db8:a::' );

// Invalid
mw.util.isIPv6Address( '2001:db8:a::/32' );
mw.util.isIPv6Address( 'hello' );

Parameters:

Name Type Attributes Default Description
address string
allowBlock boolean optional
false
Source:

Returns:

Type
boolean
Whether a string is a valid IPv6 address or not.

isInfinity(str) → {boolean}static #

Determine if an input string represents a value of infinity. This is used when testing for infinity in the context of expiries, such as watchlisting, page protection, and block expiries.

Parameters:

Name Type Description
str string | null
Source:

Returns:

Type
boolean
Determine if an input string represents a value of infinity.

isPortletVisible(portletId) → {boolean}static #

Whether a portlet is visible.

Parameters:

Name Type Description
portletId string

ID of the target portlet (e.g. 'p-cactions' or 'p-personal')

Source:

Returns:

Type
boolean
Whether a portlet is visible.

isTemporaryUser(username) → {boolean}static #

Checks if the given username matches $wgAutoCreateTempUser.

This functionality has been adapted from MediaWiki\User\TempUser\Pattern::isMatch()

Parameters:

Name Type Description
username string
Source:

Returns:

Type
boolean
Checks if the given username matches $wgAutoCreateTempUser.

parseImageUrl(url) → {ResizeableThumbnailUrl|null}static #

Parse the URL of an image uploaded to MediaWiki, or a thumbnail for such an image, and return the image name, thumbnail size and a template that can be used to resize the image.

Parameters:

Name Type Description
url string

URL to parse (URL-encoded)

Source:

Returns:

null if the URL is not a valid MediaWiki image/thumbnail URL.

Type
ResizeableThumbnailUrl | null

Parse the URL of an image uploaded to MediaWiki, or a thumbnail for such an image, and return the image name, thumbnail size and a template that can be used to resize the image.

percentDecodeFragment(text) → {string|null}static #

Percent-decode a string, as found in a URL hash fragment.

Implements the percent-decode method as defined in https://url.spec.whatwg.org/#percent-decode.

URLSearchParams implements https://url.spec.whatwg.org/#concept-urlencoded-parser which performs a '+' to ' ' substitution before running percent-decode.

To get the desired behaviour we percent-encode any '+' in the fragment to effectively expose the percent-decode implementation.

Parameters:

Name Type Description
text string

Text to decode

Source:

Returns:

Decoded text, null if decoding failed

Type
string | null
Percent-decode a string, as found in a URL hash fragment.

prettifyIP(ip) → {string|null}static #

Prettify an IP for display to end users.

This will make it more compact and lower-case.

This functionality has been adapted from \Wikimedia\IPUtils::prettifyIP()

Parameters:

Name Type Description
ip string

IP address in quad or octet form (CIDR or not).

Source:

Returns:

Type
string | null
Prettify an IP for display to end users.

rawurlencode(str) → {string}static #

Encode the string like PHP's rawurlencode.

Parameters:

Name Type Description
str string

String to be encoded.

Source:

Returns:

Encoded string

Type
string
Encode the string like PHP's rawurlencode.

sanitizeIP(ip) → {string|null}static #

Convert an IP into a verbose, uppercase, normalized form.

Both IPv4 and IPv6 addresses are trimmed. Additionally, IPv6 addresses in octet notation are expanded to 8 words; IPv4 addresses have leading zeros, in each octet, removed.

This functionality has been adapted from \Wikimedia\IPUtils::sanitizeIP()

Parameters:

Name Type Description
ip string

IP address in quad or octet form (CIDR or not).

Source:

Returns:

Type
string | null
Convert an IP into a verbose, uppercase, normalized form.

showPortlet(portletId)static #

Reveal a portlet if it is hidden.

Parameters:

Name Type Description
portletId string

ID of the target portlet (e.g. 'p-cactions' or 'p-personal')

Source:
Reveal a portlet if it is hidden.

throttle(func, wait) → {function}static #

Return a function, that, when invoked, will only be triggered at most once during a given window of time. If called again during that window, it will wait until the window ends and then trigger itself again.

As it's not knowable to the caller whether the function will actually run when the wrapper is called, return values from the function are entirely discarded.

Ported from OOUI.

Parameters:

Name Type Description
func function

Function to throttle

wait number

Throttle window length, in milliseconds

Source:

Returns:

Throttled function

Type
function

Return a function, that, when invoked, will only be triggered at most once during a given window of time.

validateEmail(email) → {boolean|null}static #

Validate a string as representing a valid e-mail address.

This validation is based on the HTML5 specification.

Example

mw.util.validateEmail( "me@example.org" ) === true;

Parameters:

Name Type Description
email string

E-mail address

Source:

Returns:

True if valid, false if invalid, null if email was empty.

Type
boolean | null
Validate a string as representing a valid e-mail address.

wikiScript(str) → {string}static #

Get URL to a MediaWiki entry point.

Similar to wfScript() in PHP.

Parameters:

Name Type Attributes Default Description
str string optional
"index"

Name of entry point (e.g. 'index' or 'api')

Since:
  • 1.18
Source:

Returns:

URL to the script file (e.g. /w/api.php)

Type
string
Get URL to a MediaWiki entry point.

wikiUrlencode(str) → {string}static #

Encode page titles in a way that matches wfUrlencode in PHP.

This is important both for readability and consistency in the user experience, as well as for caching. If URLs are not formatted in the canonical way, they may be subject to drastically shorter cache durations and/or miss automatic purging after edits, thus leading to stale content being served from a non-canonical URL.

Parameters:

Name Type Description
str string

String to be encoded.

Source:

Returns:

Encoded string

Type
string
Encode page titles in a way that matches wfUrlencode in PHP.

Type Definitions

ResizeableThumbnailUrl #

Type:

Properties:

Name Type Attributes Description
name string

File name (same format as Title.getMainText()).

width number optional

Thumbnail width, in pixels. Null when the file is not a thumbnail.

resizeUrl function optional

A function that takes a width parameter and returns a thumbnail URL (URL-encoded) with that width. The width parameter must be smaller than the width of the original image (or equal to it; that only works if MediaHandler::mustRender returns true for the file). Null when the file in the original URL is not a thumbnail. On wikis with $wgGenerateThumbnailOnParse set to true, this will fall back to using Special:Redirect which is less efficient. Otherwise, it is a direct thumbnail URL.

Source: