- Source:
Members
(static) $content
The content wrapper of the skin (e.g. .mw-body
).
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 mw.hook#wikipage_content which will
allow your code to re-run when the page changes (e.g. live preview
or re-render after ajax save).
Properties:
Type | Description |
---|---|
jQuery |
- Source:
(static) rawurlencode
Encode the string like PHP's rawurlencode
- Source:
(static) wikiUrlencode
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.
- Source:
Methods
(static) addCSS(text) → {CSSStyleSheet}
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 convience 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
(static) addPortlet(id, labelopt, beforeopt) → {HTMLElement|null
}
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
(static) addPortletLink(portletId, href, text, idopt, tooltipopt, accesskeyopt, nextnodeopt) → {HTMLElement|null
}
Add a link to a portlet menu on the page, such as:
- 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:
Fires:
Returns:
The added list item, or null if no element was added.
- Type
-
HTMLElement
|
null
(static) addSubtitle(nodeOrHTMLString)
Add content to the subtitle of the skin.
Parameters:
Name | Type | Description |
---|---|---|
nodeOrHTMLString |
HTMLElement | string |
- Source:
(static) clearSubtitle()
Clears the entire subtitle if present in the page. Used for refreshing subtitle after edit with response from parse API.
- Source:
(static) debounce(func, waitopt, immediateopt) → {function}
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
(static) escapeIdForAttribute(str) → {string}
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
(static) escapeIdForLink(str) → {string}
Encode a string as URL fragment, for use as HTML anchor link.
Analog to Sanitizer::escapeIdForLink()
in PHP.
Parameters:
Name | Type | Description |
---|---|---|
str |
string | String to encode |
- Since:
- 1.30
- Source:
Returns:
Encoded string
- Type
- string
(static) escapeRegExp(str) → {string}
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
(static) getArrayParam(param, paramsopt) → {Array.<string>|null
}
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.
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
(static) getParamValue(param, urlopt) → {string|null
}
Get the value for a given URL query parameter.
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
(static) getTargetFromFragment(hashopt) → {HTMLElement|null
}
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
(static) getUrl(pageNameopt, paramsopt) → {string}
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. |
- Source:
Returns:
URL, relative to wgServer
.
- Type
- string
(static) hidePortlet(portletId)
Hide a portlet.
Parameters:
Name | Type | Description |
---|---|---|
portletId |
string | ID of the target portlet (e.g. 'p-cactions' or 'p-personal') |
- Source:
(static) isIPAddress(address, allowBlockopt) → {boolean}
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
(static) isIPv4Address(address, allowBlockopt) → {boolean}
Whether a string is a valid IPv4 address or not.
Based on \Wikimedia\IPUtils::isIPv4 in PHP.
// 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
(static) isIPv6Address(address, allowBlockopt) → {boolean}
Whether a string is a valid IPv6 address or not.
Based on \Wikimedia\IPUtils::isIPv6 in PHP.
// 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
(static) isPortletVisible(portletId) → {boolean}
Is a portlet visible?
Parameters:
Name | Type | Description |
---|---|---|
portletId |
string | ID of the target portlet (e.g. 'p-cactions' or 'p-personal') |
- Source:
Returns:
- Type
- boolean
(static) isTemporaryUser(username) → {boolean}
Does given username match $wgAutoCreateTempUser?
This functionality has been adapted from MediaWiki\User\TempUser\Pattern::isMatch()
Parameters:
Name | Type | Description |
---|---|---|
username |
string |
- Source:
Returns:
- Type
- boolean
(static) parseImageUrl(url) → {Object|null
|string|number|function}
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:
-
URL data, or null if the URL is not a valid MediaWiki image/thumbnail URL.
- Type
-
Object
|
null
-
return.name File name (same format as Title.getMainText()).
- Type
- string
-
[return.width] Thumbnail width, in pixels. Null when the file is not a thumbnail.
- Type
- number
-
[return.resizeUrl] 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.
- Type
- function
(static) percentDecodeFragment(text) → {string|null
}
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
(static) prettifyIP(ip) → {string|null
}
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
(static) sanitizeIP(ip) → {string|null
}
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
(static) showPortlet(portletId)
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:
(static) throttle(func, wait) → {function}
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
(static) validateEmail(email) → {boolean|null
}
Validate a string as representing a valid e-mail address.
This validation is based on the HTML5 specification.
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
(static) wikiScript(stropt) → {string}
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
Events
util_addPortlet(portlet, before)
Fires when a portlet is successfully created.
Parameters:
Name | Type | Description |
---|---|---|
portlet |
HTMLElement | the portlet that was created. |
before |
string
|
null
|
the css selector used to append to the DOM. |
- Source:
Example
mw.hook( 'util.addPortlet' ).add( ( p ) => {
p.style.border = 'solid 1px black';
} );
util_addPortletLink(item, information)
Fires when a portlet link is successfully created.
Parameters:
Name | Type | Description |
---|---|---|
item |
HTMLElement | the portlet link that was created. |
information |
Object | about the item include id. |
- Source:
Example
mw.hook( 'util.addPortletLink' ).add( ( link ) => {
const span = $( '<span class="icon">' );
link.appendChild( span );
} );