Extends
Constructor
new mw.ForeignApi(url, [options])
#
Create an instance of mw.ForeignApi
.
Parameters:
Name | Type | Attributes | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
url |
string | URL pointing to another wiki's |
|||||||||||
options |
mw.Api.Options |
optional |
Also accepts all the options from Properties:
|
- Since:
- 1.26
- Source:
Methods
abort()
#
Abort all unfinished requests issued by this Api object.
- Inherited from:
- Source:
ajax(parameters, [ajaxOptions]) → {jQuery.Promise}
#
Perform the API call.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
parameters |
Object | Parameters to the API. See also |
|
ajaxOptions |
Object |
optional |
Parameters to pass to jQuery.ajax. See also
|
- Inherited from:
- Source:
Returns:
A promise that settles when the API response is processed. Has an 'abort' method which can be used to abort the request.
- On success, resolves to
( result, jqXHR )
whereresult
is the parsed API response. - On an API error, rejects with
( code, result, result, jqXHR )
wherecode
is the API error code, andresult
is as above. When there are multiple errors, the code from the first one will be used. If there is no error code, "unknown" is used. - On other types of errors, rejects with
( 'http', details )
wheredetails
is an object with three fields:xhr
(the jqXHR object),textStatus
, andexception
. The meaning of the last two fields is as follows:- When the request is aborted (the abort method of the promise is called), textStatus and exception are both set to "abort".
- On a network timeout, textStatus and exception are both set to "timeout".
- On a network error, textStatus is "error" and exception is the empty string.
- When the HTTP response code is anything other than 2xx or 304 (the API does not
use such response codes but some intermediate layer might), textStatus is "error"
and exception is the HTTP status text (the text following the status code in the
first line of the server response). For HTTP/2,
exception
is always an empty string. - When the response is not valid JSON but the previous error conditions aren't met,
textStatus is "parsererror" and exception is the exception object thrown by
JSON.parse
.
- Type
- jQuery.Promise
assertCurrentUser(query) → {Object}
#
Extend an API parameter object with an assertion that the user won't change.
This is useful for API calls which create new revisions or log entries. When the current page was loaded when the user was logged in, but at the time of the API call the user is not logged in anymore (e.g. due to session expiry), their IP is recorded in the page history or log, which can cause serious privacy issues. Extending the API parameters via this method ensures that that won't happen, by checking the user's identity that was embedded into the page when it was rendered against the active session on the server.
When the assertion fails, the API request will fail, with one of the following error codes:
- apierror-assertanonfailed: when the client-side logic thinks the user is anonymous but the server thinks it is logged in;
- apierror-assertuserfailed: when the client-side logic thinks the user is logged in but the server thinks it is anonymous;
- apierror-assertnameduserfailed: when both the client-side logic and the server thinks the user is logged in but they see it logged in under a different username.
Example
api.postWithToken( 'csrf', api.assertCurrentUser( { action: 'edit', ... } ) )
Parameters:
Name | Type | Description |
---|---|---|
query |
Object | Query parameters. The object will not be changed. |
- Since:
- 1.27
- Inherited from:
- Source:
Returns:
- Type
- Object
badToken(type)
#
Indicate that the cached token for a certain action of the API is bad.
Call this if you get a 'badtoken' error when using the token returned by getToken()
.
You may also want to use postWithToken()
instead, which invalidates bad cached tokens
automatically.
Parameters:
Name | Type | Description |
---|---|---|
type |
string | Token type |
- Since:
- 1.26
- Inherited from:
- Source:
chunkedUpload(file, data, [chunkSize], [chunkRetries]) → {jQuery.Promise}
#
Upload a file in several chunks.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
file |
File | ||
data |
Object | Other upload options, see action=upload API docs for more |
|
chunkSize |
number |
optional |
Size (in bytes) per chunk (default: 5 MiB) |
chunkRetries |
number |
optional |
Amount of times to retry a failed chunk (default: 1) |
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
chunkedUploadToStash(file, [data], [chunkSize], [chunkRetries]) → {jQuery.Promise.<function(Object): jQuery.Promise>}
#
Upload a file to the stash, in chunks.
This function will return a promise, which when resolved, will pass back a function to finish the stash upload.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
file |
File | HTMLInputElement | ||
data |
Object |
optional |
|
chunkSize |
number |
optional |
Size (in bytes) per chunk (default: 5 MiB) |
chunkRetries |
number |
optional |
Amount of times to retry a failed chunk (default: 1) |
- Inherited from:
- Source:
- See:
Returns:
Promise that resolves with a function that should be called to finish the upload.
- Type
- jQuery.Promise.<function(Object): jQuery.Promise>
create(title, params, content) → {jQuery.Promise}
#
Create a new page.
Example
new mw.Api().create( 'Sandbox',
{ summary: 'Load sand particles.' },
'Sand.'
);
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
title |
mw.Title | string | Page title |
||||||
params |
Object | Edit API parameters Properties:
|
||||||
content |
string |
- Since:
- 1.28
- Inherited from:
- Source:
Returns:
API response
- Type
- jQuery.Promise
edit(title, transform) → {jQuery.Promise}
#
Edit an existing page.
To create a new page, use #create() instead.
Simple transformation:
new mw.Api()
.edit( 'Sandbox', function ( revision ) {
return revision.content.replace( 'foo', 'bar' );
} )
.then( function () {
console.log( 'Saved!' );
} );
Set save parameters by returning an object instead of a string:
new mw.Api().edit(
'Sandbox',
function ( revision ) {
return {
text: revision.content.replace( 'foo', 'bar' ),
summary: 'Replace "foo" with "bar".',
assert: 'bot',
minor: true
};
}
)
.then( function () {
console.log( 'Saved!' );
} );
Transform asynchronously by returning a promise.
new mw.Api()
.edit( 'Sandbox', function ( revision ) {
return Spelling
.corrections( revision.content )
.then( function ( report ) {
return {
text: report.output,
summary: report.changelog
};
} );
} )
.then( function () {
console.log( 'Saved!' );
} );
Parameters:
Name | Type | Description |
---|---|---|
title |
mw.Title | string | Page title |
transform |
mw.Api.EditTransform | Callback that prepares the edit |
- Since:
- 1.28
- Inherited from:
- Source:
Returns:
Edit API response
- Type
- jQuery.Promise
get(parameters, [ajaxOptions]) → {jQuery.Promise}
#
Perform API get request. See ajax()
for details.
Parameters:
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
getCategories(title) → {jQuery.Promise.<(Array.<mw.Title>|false)>}
#
Get the categories that a particular page on the wiki belongs to.
Parameters:
- Inherited from:
- Source:
Returns:
Promise that resolves with an array of category titles, or with false if the title was not found.
- Type
- jQuery.Promise.<(Array.<mw.Title>|false)>
getCategoriesByPrefix(prefix) → {jQuery.Promise.<Array.<string>>}
#
Get a list of categories that match a certain prefix.
E.g. given "Foo", return "Food", "Foolish people", "Foosball tables"...
Parameters:
Name | Type | Description |
---|---|---|
prefix |
string | Prefix to match. |
- Inherited from:
- Source:
Returns:
Promise that resolves with an array of matched categories
- Type
- jQuery.Promise.<Array.<string>>
getEditToken() → {jQuery.Promise}
#
API helper to grab a csrf token.
- Inherited from:
- Source:
Returns:
Received token.
- Type
- jQuery.Promise
getErrorMessage(data) → {jQuery}
#
Given an API response indicating an error, get a jQuery object containing a human-readable error message that you can display somewhere on the page.
For better quality of error messages, it's recommended to use the following options in your API queries:
errorformat: 'html',
errorlang: mw.config.get( 'wgUserLanguage' ),
errorsuselocal: true,
Error messages, particularly for editing pages, may consist of multiple paragraphs of text. Your user interface should have enough space for that.
Example
var api = new mw.Api();
// var title = 'Test valid title';
var title = 'Test invalid title <>';
api.postWithToken( 'watch', {
action: 'watch',
title: title
} ).then( ( data ) => {
mw.notify( 'Success!' );
}, ( code, data ) => {
mw.notify( api.getErrorMessage( data ), { type: 'error' } );
} );
Parameters:
Name | Type | Description |
---|---|---|
data |
Object | API response indicating an error |
- Inherited from:
- Source:
Returns:
Error messages, each wrapped in a <div>
- Type
- jQuery
Given an API response indicating an error, get a jQuery object containing a human-readable error message that you can display somewhere on the page.
getMessages(messages, [options]) → {jQuery.Promise.<Object.<string, string>>}
#
getToken(type, [additionalParams]) → {jQuery.Promise.<string>}
#
Get a token for a certain action from the API.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
type |
string | Token type |
|
additionalParams |
Object | string |
optional |
Additional parameters for the API (since 1.35). When given a string, it's treated as the 'assert' parameter (since 1.25). |
- Since:
- 1.22
- Inherited from:
- Source:
Returns:
Received token.
- Type
- jQuery.Promise.<string>
getUserInfo() → {jQuery.Promise.<mw.Api.UserInfo>}
#
Get the current user's groups and rights.
- Since:
- 1.27
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise.<mw.Api.UserInfo>
isCategory(title) → {jQuery.Promise.<boolean>}
#
Determine if a category exists.
Parameters:
- Inherited from:
- Source:
Returns:
Promise that resolves with a boolean indicating whether the category exists.
- Type
- jQuery.Promise.<boolean>
loadMessages(messages, [options]) → {jQuery.Promise}
#
Loads a set of messages and add them to mw.messages
.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
messages |
string | Array.<string> | Messages to retrieve |
|
options |
Object |
optional |
Additional parameters for the API call |
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
mw.messages
.
loadMessagesIfMissing(messages, [options]) → {jQuery.Promise}
#
Loads a set of messages and add them to mw.messages
. Only messages that are not already known
are loaded. If all messages are known, the returned promise is resolved immediately.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
messages |
string | Array.<string> | Messages to retrieve |
|
options |
Object |
optional |
Additional parameters for the API call |
- Since:
- 1.27
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
mw.messages
.
login(username, password) → {jQuery.Promise}
#
newSection(title, header, message, [additionalParams]) → {jQuery.Promise}
#
Post a new section to the page.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
title |
mw.Title | string | Target page |
|
header |
string | ||
message |
string | wikitext message |
|
additionalParams |
Object |
optional |
Additional API parameters, e.g. |
- Inherited from:
- Source:
- See:
Returns:
- Type
- jQuery.Promise
parse(content, additionalParams) → {jQuery.Promise.<string>}
#
Convenience method for 'action=parse'.
Parameters:
Name | Type | Description |
---|---|---|
content |
string | mw.Title | Content to parse, either as a wikitext string or a mw.Title. |
additionalParams |
Object | Parameters object to set custom settings, e.g.
|
- Inherited from:
- Source:
Returns:
Promise that resolves with the parsed HTML of wikitext
- Type
- jQuery.Promise.<string>
post(parameters, [ajaxOptions]) → {jQuery.Promise}
#
Perform API post request. See ajax()
for details.
Parameters:
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
postWithEditToken(params, [ajaxOptions]) → {jQuery.Promise}
#
Post to API with csrf
token. See #postWithToken
Parameters:
- Inherited from:
- Source:
Returns:
See #post
- Type
- jQuery.Promise
csrf
token.
postWithToken(tokenType, params, [ajaxOptions]) → {jQuery.Promise}
#
Post to API with the specified type of token. If we have no token, get one and try to post. If we already have a cached token, try using that, and if the request fails using the cached token, blank it out and start over.
Example
new mw.Api().postWithToken( 'csrf', {
action: 'options',
optionname: 'gender',
optionvalue: 'female'
} );
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
tokenType |
string | The name of the token, like options or edit. |
|
params |
Object | API parameters |
|
ajaxOptions |
Object |
optional |
- Since:
- 1.22
- Inherited from:
- Source:
Returns:
See post()
- Type
- jQuery.Promise
prepareExtensibleApiRequest(hookName) → {jQuery.Promise.<Object>}
#
Prepare an extensible API request.
This is a utility method to allow mw.hook implementations to add data to params sent with an API request.
For example usage, see mediawiki.ready/index.js#logoutViaPost: api.prepareExtensibleApiRequest( 'extendLogout' ).then( ( params ) => { ... } )
Implementations of hookName
should do something like the following, where hookName
is extendLogout
in this example:
mw.hook( 'extendLogout' ).add( ( data ) => { data.promise = data.promise.then( () => { // Return a promise return collectClientHintsData().then( ( userAgentHighEntropyValues ) => { // Set the data.params.{yourUniqueKey} that will be included in the API // request data.params.customData = { clientHints: userAgentHighEntropyValues }; } ); } ); } );
Parameters:
Name | Type | Description |
---|---|---|
hookName |
string | Name of the hook to use with mw.hook().fire() |
- Inherited from:
- Source:
Returns:
Updated parameter data from implementations
of hookName
to include with the API request.
- Type
- jQuery.Promise.<Object>
rollback(page, user, [params]) → {jQuery.Promise}
#
Convenience method for action=rollback
.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
page |
string | mw.Title | ||
user |
string | ||
params |
Object |
optional |
Additional parameters |
- Since:
- 1.28
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
action=rollback
.
saveOption(name, value, [params]) → {jQuery.Promise}
#
Asynchronously save the value of a single user option using the API.
See saveOptions()
.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
name |
string | ||
value |
string
|
null
|
||
params |
Object |
optional |
additional parameters for API. |
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
saveOptions(options, [params]) → {jQuery.Promise}
#
Asynchronously save the values of user options using the Options API.
If a value of null
is provided, the given option will be reset to the default value.
Any warnings returned by the API, including warnings about invalid option names or values, are ignored. However, do not rely on this behavior.
If necessary, the options will be saved using several sequential API requests. Only one promise is always returned that will be resolved when all requests complete.
If a request from a previous saveOptions()
call is still pending, this will wait for it to be
completed, otherwise MediaWiki gets sad. No requests are sent for anonymous users, as they
would fail anyway. See T214963.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
Object | Options as a |
|
params |
Object |
optional |
additional parameters for API. |
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
Asynchronously save the values of user options using the Options API.
unwatch(pages) → {jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>}
#
Convenience method for action=watch&unwatch=1
.
Parameters:
Name | Type | Description |
---|---|---|
pages |
string | mw.Title | Array.<string> | Array.<mw.Title> | Full page name or instance of mw.Title, or an array thereof. If an array is passed, the return value passed to the promise will also be an array of appropriate objects. |
- Inherited from:
- Source:
Returns:
A promise that resolves with an object (or array of objects) describing each page that was passed in and its current watched/unwatched status.
- Type
- jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>
action=watch&unwatch=1
.
upload(file, data) → {jQuery.Promise}
#
Upload a file to MediaWiki.
The file will be uploaded using AJAX and FormData.
Parameters:
Name | Type | Description |
---|---|---|
file |
HTMLInputElement | File | Blob | HTML input type=file element with a file already inside of it, or a File object. |
data |
Object | Other upload options, see action=upload API docs for more |
- Inherited from:
- Source:
Returns:
- Type
- jQuery.Promise
uploadFromStash(filekey, data) → {jQuery.Promise}
#
uploadToStash(file, [data]) → {jQuery.Promise.<function(Object): jQuery.Promise>}
#
Upload a file to the stash.
This function will return a promise, which when resolved, will pass back a function to finish the stash upload. You can call that function with an argument containing more, or conflicting, data to pass to the server.
Example
// upload a file to the stash with a placeholder filename
api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
// finish is now the function we can use to finalize the upload
// pass it a new filename from user input to override the initial value
finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
// the upload is complete, data holds the API response
} );
} );
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
file |
File | HTMLInputElement | ||
data |
Object |
optional |
- Inherited from:
- Source:
Returns:
Promise that resolves with a function that should be called to finish the upload.
- Type
- jQuery.Promise.<function(Object): jQuery.Promise>
watch(pages, [expiry]) → {jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>}
#
Convenience method for action=watch
.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
pages |
string | mw.Title | Array.<string> | Array.<mw.Title> | Full page name or instance of mw.Title, or an array thereof. If an array is passed, the return value passed to the promise will also be an array of appropriate objects. |
|
expiry |
string |
optional |
When the page should expire from the watchlist. If omitted, the page will not expire. |
- Since:
- 1.35 - expiry parameter can be passed when Watchlist Expiry is enabled
- Inherited from:
- Source:
Returns:
A promise that resolves with an object (or array of objects) describing each page that was passed in and its current watched/unwatched status.
- Type
- jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>
action=watch
.