Jump to content

User:Polygnotus/Scripts/EditAsMe.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Intercept all MediaWiki API calls and add assertuser to prevent any action
// being attributed to an IP or temporary user if the session expires.
mw.loader.using( 'mediawiki.api' ).then( function () {
    var userName = mw.config.get( 'wgUserName' );
    if ( !userName ) {
        return;
    }
    var originalAjax = mw.Api.prototype.ajax;
    mw.Api.prototype.ajax = function ( parameters, ajaxOptions ) {
        parameters = Object.assign( {}, parameters, {
            assertuser: userName
        } );
        var request = originalAjax.call( this, parameters, ajaxOptions );
        var promise = request.catch( function ( code ) {
            if ( code === 'assertuserfailed' || code === 'assertnameduserfailed' ) {
                mw.notify(
                    'Your session has expired. Please log in again.',
                    { type: 'error', autoHide: false }
                );
            }
            return $.Deferred().reject.apply( null, arguments ).promise();
        } );
        // Forward abort() from the original jqXHR to the returned promise
        promise.abort = function () {
            return request.abort();
        };
        return promise;
    };
} );