ResourceLoader/Core modules/zh

本页列出MediaWiki 的默认类库、插件和脚本，并且给出用法说明和例子. 本页可能没有包括进MediaWiki的最近更新，所以望读者踊跃更新本页.

本页的模块顺序与保持一致. 模块里面的对象的顺序应当是有意义的，可以跟代码中的定义保持一致，或按字母顺序排列. 如果一个模块里仅有一个对象，那么该模块的章节里就不需要有一个单独的标题.

JSDuck documentation是根据MediaWiki的文档注释自动生成的文档. 此文档有最全的模块和对象，但用法和例子可能不如本文多.

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


 * For a complete list of configuration values in, 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.

See the code for more information and examples.
 * : A framework for registering and firing events in JavaScript (as opposed to doing everything on document ready).


 * : Escape a string for HTML. Converts special characters to HTML entities.


 * : Creates an HTML string, with safe escaping.


 * See also Manual:Messages API

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

Returns a new instance of Message. is a shortcut to this with output using the text format (however, without jqueryMsg, this is equivalent to the plain format). See Localisation for information about using PLURAL, GENDER, and more advanced message features in JavaScript.


 * : Key of the message
 * : (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.)

This is a shortcut for creating an instance of Message via  and returning

mw.loader.addSource
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.getModuleNames
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
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.

mw.loader.getVersion
Returns the version of a module, or  if it is not in the registry.

mw.loader.go
No longer needed,  takes an array to load multiple modules in one request.

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

mw.loader.load
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. "" Note: mediaWiki.loader do not accept relative urls (see bug 34036) and differently from jQuery.getScript, it doesn't support callback functions (bug 25962).

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

mw.loader.state
Changes the state of the module.

mw.loader.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.version
Use.

mw.loader.work
Processing function to load and execute modules

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) 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.

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

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


 * : An object containing all the variables. If 'global' was true during initialization, this is an alias to the  object.
 * : Function returns true if an entry with the key(s) exists, false otherwise
 * : 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)
 * : Creates / Modifies one or multiple values

Examples

Address Book example

mw.user.anonymous
Use  instead.

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

mw.user.id
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.

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

mw.user.name
Use  instead.

sessionId
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.

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

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

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

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

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

The base  plugin provides two methods that take a raw API query:
 * Api.get
 * Api.post

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#post
Like, takes a raw API query, but prepares   internally for a POST request instead.

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

mw.Api#errors
List of errors that could be received from the API.

mw.Api#warnings
List of warnings that could be received from API.

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

mw.Api#isCategory
Determines if a category exists.

mw.Api#getCategoriesByPrefix
Lists categories with a given prefix.

mw.Api#getCategories
Gets the list of categories that a given page belongs to.

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

mw.Api#postWithEditToken
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
This is a low-level method used by api.postWithEditToken to get tokens.

mw.Api#newSection
Creates a new section on the given page, with the given section name and text.

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

mw.Api#parse
Calls the server to parse the given wikitext. Example:

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
Determines if a given mw.Title is blacklisted.

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

mw.Api#watch
Watches a given title.

mw.Api#unwatch
Unwatches a given title.

mw.Debug.init
Initializes the debugging pane.

mw.Debug.switchPane
Switches between debug panes.

mw.Debug.buildHtml
Builds HTML for the toolbar.

mw.Debug.buildConsoleTable
Builds the console pane.

mw.Debug.buildQueryTable
Builds the SQL pane.

mw.Debug.buildDebugLogTable
Builds logging pane (legacy).

mw.Debug.buildRequestPane
Builds requests pane.

mw.Debug.buildIncludesPane
Builds included files pane.

Calls mw.Debug.init.

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

mw.Feedback.setup
Sets up feedback GUI.

mw.Feedback.display
Displays a particular part of the feedback interface.

mw.Feedback.displaySubmitting
Shows that the feedback is being added.

mw.Feedback.displayBugs
Shows information about bug tracker

mw.Feedback.displayThanks
Shows thank you message.

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

mw.Feedback.displayError
Shows given error message.

mw.Feedback.cancel
Dismisses feedback form.

mw.Feedback.submit
Submits feedback form using mw.Api.newSection.

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


 * See also Manual:Messages API

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.

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.

addCSS
Adds a  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.

addPortletLink
加入入口链接. 此方法移植自已过时的wikibits，并与它向下兼容. addPortletLink支持主要皮肤（core skins），有 参数可以指定加入的入口链接的位置.

如果你想在点击链接时执行JavaScript，设置href为#，然后在jQuery(...).click里面编写执行的代码.

可以是
 * p-cactions：正文动作(Content actions)，“查看历史”“监视此页面”右边的下拉箭头
 * p-personal：用户工具(Personal tools)，“用户贡献”“监视列表”一行.
 * p-navigation：导航栏(Navigation)，维基球下面，“首页”“分类索引”一列.
 * p-tb：工具箱(toolbox)，在导航栏下面.

：推荐按照加入的位置，以“ca-”“pt-”“n-”“t-”开头.

：类型HTMLElement或jQuery或string. 如果为空，则入口链接加在列表末尾.

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

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  instead.

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.

getParamValue
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  if the parameter is not present. Returns an empty string if it was an empty parameter (such as

jsMessage
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.

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

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

validateEmail
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.

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

wikiGetlink
This function returns the address to a local wiki page.

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

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

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

Basic examples

Basic examples

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/


 * Plugin documentation

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

 * can be a number or a string. If the value is falsey (0, null, false, '', etc.), any existing badge will be removed.
 * 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
This single-function plugin can be called to add this functionality to any number of checkboxes. By default (onload) it's applied to all  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).

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
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:

Here a few examples Check for possible values of browser names, layout engines and platforms.

jQuery.client.test
...

Used by the Vector extension.


 * getRGB
 * colors
 * rgbToHsl
 * hslToRgb
 * getColorBrightness

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

jQuery#cookie
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.

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

Project home page


 * See also Manual:Collapsible elements.

Plugin makes all passed elements collapsible. It supports lots of variations such as:
 * Simple: Add " " 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 '" '" as additional class will cause the element to be initially collapsed when the page is loaded.
 * Custom label:HTML5 only Using the  and   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:


 * Remote toggle: If you don't want the script to put the default toggle link (wether 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  and   for the collapsible element and the togglelink respectively.

Example: Simple collapsible div or table

Input:

Output:

This is text is collapsible.

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

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

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.

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

CompletenessTest
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 when running the QUnit test suite with the   option enabled.

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

Real world examples: ,

Example shows suggestions for the summary-line:

Example page; JQuery project page

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 94227).

jQuery.trimLeft
Trims whitespace from the left side of the string

jQuery.trimRight
Trims whitespace from the right of the string

jQuery.ucFirst
Returns the string with the first character capitalized

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

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

jQuery.isEmpty
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
Compares two arrays and returns a boolean for whether they are in fact the same

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

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

The following components are included:
 * jquery.ui.accordion.js
 * jquery.ui.autocomplete.js
 * jquery.ui.button.js
 * jquery.ui.core.js
 * jquery.ui.datepicker.js
 * jquery.ui.dialog.js
 * jquery.ui.draggable.js
 * jquery.ui.droppable.js
 * jquery.ui.mouse.js
 * jquery.ui.position.js
 * jquery.ui.progressbar.js
 * jquery.ui.resizable.js
 * jquery.ui.selectable.js
 * jquery.ui.slider.js
 * jquery.ui.sortable.js
 * jquery.ui.tabs.js
 * jquery.ui.widget.js