Expand all

mw.ForeignApi

Interact with the API of another MediaWiki site. mw.Foreign API creates an object like mw.Api, but automatically handle everything required to communicate with another MediaWiki wiki via cross-origin requests (CORS).

The foreign wiki must be configured to accept requests from the current wiki. See https://www.mediawiki.org/wiki/Manual:$wgCrossSiteAJAXdomains for details.

const api = new mw.ForeignApi( 'https://commons.wikimedia.org/w/api.php' );
api.get( {
    action: 'query',
    meta: 'userinfo'
} ).done( function ( data ) {
    console.log( data );
} );

To ensure that the user at the foreign wiki is logged in, pass the assert: 'user' parameter to get()/post() (since MW 1.23), otherwise the API request will fail. (Note that this doesn't guarantee that it's the same user. To assert that the user at the foreign wiki has a specific username, pass the assertuser parameter with the desired username.)

Authentication-related MediaWiki extensions may extend this class to ensure that the user authenticated on the current wiki will be automatically authenticated on the foreign one. These extension modules should be registered using the ResourceLoaderForeignApiModules hook. See CentralAuth for a practical example. The general pattern to extend and override the name is:

function MyForeignApi() {};
OO.inheritClass( MyForeignApi, mw.ForeignApi );
mw.ForeignApi = MyForeignApi;

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 api.php endpoint.

options mw.Api.Options optional

Also accepts all the options from mw.Api.Options.

Properties:
Name Type Attributes Default Description
anonymous boolean optional
false

Perform all requests anonymously. Use this option if the target wiki may otherwise not accept cross-origin requests, or if you don't need to perform write actions or read restricted information and want to avoid the overhead.

Since:
  • 1.26
Author:
  • Bartosz Dziewoński
  • Jon Robson
Source:

Methods

abort() #

Abort all unfinished requests issued by this Api object.

Inherited from:
Source:
Abort all unfinished requests issued by this Api object.

ajax(parameters, [ajaxOptions]) → {jQuery.Promise} #

Perform the API call.

Parameters:

Name Type Attributes Description
parameters Object

Parameters to the API. See also mw.Api.Options

ajaxOptions Object optional

Parameters to pass to jQuery.ajax. See also mw.Api.Options

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 ) where result is the parsed API response.
  • On an API error, rejects with ( code, result, result, jqXHR ) where code is the API error code, and result 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 ) where details is an object with three fields: xhr (the jqXHR object), textStatus, and exception. 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
Perform the API call.

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
Extend an API parameter object with an assertion that the user won't change.

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:
Indicate that the cached token for a certain action of the API is bad.

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
Upload a file in several chunks.

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>
Upload a file to the stash, in chunks.

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:
Name Type Description
summary string

Edit summary

content string
Since:
  • 1.28
Inherited from:
Source:

Returns:

API response

Type
jQuery.Promise
Create a new page.

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
Edit an existing page.

get(parameters, [ajaxOptions]) → {jQuery.Promise} #

Perform API get request. See ajax() for details.

Parameters:

Name Type Attributes Description
parameters Object
ajaxOptions Object optional
Inherited from:
Source:

Returns:

Type
jQuery.Promise
Perform API get request.

getCategories(title) → {jQuery.Promise.<(Array.<mw.Title>|false)>} #

Get the categories that a particular page on the wiki belongs to.

Parameters:

Name Type Description
title mw.Title | string
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)>
Get the categories that a particular page on the wiki belongs to.

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>>
Get a list of categories that match a certain prefix.

getEditToken() → {jQuery.Promise} #

API helper to grab a csrf token.

Inherited from:
Source:

Returns:

Received token.

Type
jQuery.Promise
API helper to grab a csrf token.

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>>} #

Get a set of messages.

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.<Object.<string, string>>
Get a set of messages.

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>
Get a token for a certain action from the API.

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>
Get the current user's groups and rights.

isCategory(title) → {jQuery.Promise.<boolean>} #

Determine if a category exists.

Parameters:

Name Type Description
title mw.Title | string
Inherited from:
Source:

Returns:

Promise that resolves with a boolean indicating whether the category exists.

Type
jQuery.Promise.<boolean>
Determine if a category exists.

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
Loads a set of messages and add them to 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
Loads a set of messages and add them to mw.messages.

login(username, password) → {jQuery.Promise} #

Parameters:

Name Type Description
username string
password string
Inherited from:
Source:

Returns:

See post()

Type
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. { redirect: true }

Inherited from:
Source:
See:

Returns:

Type
jQuery.Promise
Post a new section to the page.

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. redirects, sectionpreview. prop should not be overridden.

Inherited from:
Source:

Returns:

Promise that resolves with the parsed HTML of wikitext

Type
jQuery.Promise.<string>
Convenience method for 'action=parse'.

post(parameters, [ajaxOptions]) → {jQuery.Promise} #

Perform API post request. See ajax() for details.

Parameters:

Name Type Attributes Description
parameters Object
ajaxOptions Object optional
Inherited from:
Source:

Returns:

Type
jQuery.Promise
Perform API post request.

postWithEditToken(params, [ajaxOptions]) → {jQuery.Promise} #

Post to API with csrf token. See #postWithToken

Parameters:

Name Type Attributes Description
params Object

API parameters

ajaxOptions Object optional
Inherited from:
Source:

Returns:

See #post

Type
jQuery.Promise
Post to API with 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

For example, to change a user option, you could do:

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
Post to API with the specified type of token.

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>
Prepare an extensible API request.

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
Convenience method for 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
Asynchronously save the value of a single user option using the API.

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 { name: value, … } object

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>)>
Convenience method for 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
Upload a file to MediaWiki.

uploadFromStash(filekey, data) → {jQuery.Promise} #

Finish an upload in the stash.

Parameters:

Name Type Description
filekey string
data Object
Inherited from:
Source:

Returns:

Type
jQuery.Promise
Finish an upload in the stash.

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>
Upload a file to the stash.

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>)>
Convenience method for action=watch.