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;
- Source:
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:
.mw-body
, for example).
Methods
$.fn.updateTooltipAccessKeys() → {jQuery}staticchainable
#
Update the titles for all elements in a jQuery selection.
To use this jQuery
plugin, load the mediawiki.util
module using mw.loader
.
Example
// Converts tooltip "[z]" to associated browser shortcut key e.g. "[ctrl-option-z]"
mw.loader.using( 'mediawiki.util' ).then( () => {
var $a = $('<a href="/wiki/Main_Page" title="Visit the main page [z]" accesskey="z"><span>Main page</span></a>');
$a.updateTooltipAccessKeys();
} );
Returns:
- Type
- jQuery
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
addPortlet(id, [label], [selectorHint]) → {HTMLElement|null
}static
#
null
}static
#
Creates a detached portlet Element in the skin with no elements.
Example
// Create a portlet with 2 menu items that is styled as a dropdown in certain skins.
const p = mw.util.addPortlet( 'p-myportlet', 'My label', '#p-cactions' );
mw.util.addPortletLink( 'p-myportlet', '#', 'Link 1' );
mw.util.addPortletLink( 'p-myportlet', '#', 'Link 2' );
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
id |
string | of the new portlet. |
|
label |
string |
optional |
of the new portlet. |
selectorHint |
string |
optional |
selector of the element the new portlet would like to
be inserted near. Typically the portlet will be inserted after this selector, but in some
skins, the skin may relocate the element when provided to the closest available space.
If this argument is not passed then the caller is responsible for appending the element
to the DOM before using addPortletLink.
To add a portlet in an exact position do not rely on this parameter, instead using the return
element (make sure to also assign the result to a variable), use
|
- Source:
Returns:
will be null if it was not possible to create an portlet with
the required information e.g. the selector given in selectorHint
parameter could not be resolved
to an existing element in the page.
- Type
-
HTMLElement
|
null
Fires:
addPortletLink(portletId, href, text, [id], [tooltip], [accesskey], [nextnode]) → {HTMLElement|null
}static
#
null
}static
#
Add a link to a portlet menu on the page.
The portlets that are supported include:
- p-cactions (Content actions)
- p-personal (Personal tools)
- p-navigation (Navigation)
- p-tb (Toolbox)
- p-associated-pages (For namespaces and special page tabs on supported skins)
- p-namespaces (For namespaces on legacy skins)
Additional menus can be discovered through the following code:
$('.mw-portlet').toArray().map((el) =>
el.id
);
Menu availability varies by skin, wiki, and current page.
The first three parameters are required, the others are optional and may be null. Though providing an id and tooltip is recommended.
By default, the new link will be added to the end of the menu. To
add the link before an existing item, pass the DOM node or a CSS selector
for that item, e.g. '#foobar'
or document.getElementById( 'foobar' )
.
mw.util.addPortletLink(
'p-tb', 'https://www.mediawiki.org/',
'mediawiki.org
', 't-mworg', 'Go to mediawiki.org
', 'm', '#t-print'
);
var node = mw.util.addPortletLink(
'p-tb',
mw.util.getUrl( 'Special:Example' ),
'Example'
);
$( node ).on( 'click', function ( e ) {
console.log( 'Example' );
e.preventDefault();
} );
Remember that to call this inside a user script, you may have to ensure the
mediawiki.util
is loaded first:
$.when( mw.loader.using( [ 'mediawiki.util' ] ), $.ready ).then( function () {
mw.util.addPortletLink( 'p-tb', 'https://www.mediawiki.org/', 'mediawiki.org
' );
} );
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
portletId |
string | ID of the target portlet (e.g. 'p-cactions' or 'p-personal') |
|
href |
string | Link URL |
|
text |
string | Link text |
|
id |
string |
optional |
ID of the list item, should be unique and preferably have the appropriate prefix ('ca-', 'pt-', 'n-' or 't-') |
tooltip |
string |
optional |
Text to show when hovering over the link, without accesskey suffix |
accesskey |
string |
optional |
Access key to activate this link. One character only,
avoid conflicts with other links. Use |
nextnode |
HTMLElement | jQuery | string |
optional |
Element that the new item should be added before. Must be another item in the same list, it will be ignored otherwise. Can be specified as DOM reference, as jQuery object, or as CSS selector string. |
- Source:
Returns:
The added list item, or null if no element was added.
- Type
-
HTMLElement
|
null
Fires:
addSubtitle(nodeOrHTMLString)static
#
Add content to the subtitle of the skin.
Parameters:
Name | Type | Description |
---|---|---|
nodeOrHTMLString |
HTMLElement | string |
- Source:
clearSubtitle()static
#
Clears the entire subtitle if present in the page. Used for refreshing subtitle after edit with response from parse API.
- Source:
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
#
escapeIdForLink(str) → {string}static
#
escapeRegExp(str) → {string}static
#
getArrayParam(param, [params]) → {Array.<string>|null
}static
#
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.
getParamValue(param, [url]) → {string|null
}static
#
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
getTargetFromFragment([hash]) → {HTMLElement|null
}static
#
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
getUrl([pageName], [params]) → {string}static
#
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:
isIPAddress(address, [allowBlock]) → {boolean}static
#
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:
- Source:
Returns:
- Type
- boolean
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:
- Source:
Returns:
- Type
- boolean
isInfinity(str) → {boolean}static
#
isPortletVisible(portletId) → {boolean}static
#
isTemporaryUser(username) → {boolean}static
#
messageBox(textOrElement, [type], [inline]) → {Element}static
#
Create a message box element. Callers are responsible for ensuring suitable Codex styles have been added to the page e.g. mediawiki.codex.messagebox.styles.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
textOrElement |
string | Node | text or node. |
|
type |
string |
optional |
defaults to notice. |
inline |
boolean |
optional |
whether the notice should be inline. |
- Since:
- 1.43
- Source:
Returns:
- Type
- Element
parseImageUrl(url) → {ResizeableThumbnailUrl|null
}static
#
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
#
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
prettifyIP(ip) → {string|null
}static
#
null
}static
#
rawurlencode(str) → {string}static
#
sanitizeIP(ip) → {string|null
}static
#
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
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:
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
#
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
wikiScript([str]) → {string}static
#
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
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: