Jump to content

User:Zackmann08/scripts/rollback.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.
// <nowiki>

function waitForElement(selector) {
  return new Promise(resolve => {
    // Check if it already exists
    const element = document.querySelector(selector);
    if (element) {
      return resolve(element);
    }

    // Observe changes if it doesn't exist yet
    const observer = new MutationObserver(mutations => {
      const element = document.querySelector(selector);
      if (element) {
        resolve(element);
        observer.disconnect(); // Stop observing once found
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  });
}

function unknownRollback(){
	mw.notify('Rolling back unknown addition...', {type: 'warn'});
	var oldid = document.getElementById('mw-diff-otitle1').querySelector('a').href.match(/\d+$/)[0];
	
	mw.loader.using("mediawiki.api", function () {
    	var api = new mw.Api();
		api.get( {
		    action: 'query',
		    prop: 'revisions',
		    revids: oldid,
		    rvprop: 'content',
		    rvslots: 'main'
		} ).then( function ( data ) {
		    // Access the text from the response
		    var pageId = Object.keys(data.query.pages)[0];
		    var content = data.query.pages[pageId].revisions[0].slots.main['*'];
			api.postWithEditToken( {
	            action: "edit",
	            title: mw.config.get('wgPageName'),
	            undoafter: oldid,
	            undo: mw.config.get('wgCurRevisionId'),
	            summary: 'Edit(s) introduced 1 or more [[CAT:UNKNOWN|unknown parameters]], therefore reverting. Please [[WP:PREVIEW|preview]] your edits to check for errors.',
	            text: content
	        }).done ( function ( data ) {
	            if ( data && data.edit && data.edit.result && data.edit.result == 'Success' ) {
	            	var talk_page = document.querySelector('#mw-diff-ntitle2 .mw-usertoollinks a').href;
	            	document.querySelector('#ca-view a').click();
	            	window.open(talk_page, '_blank');
	            	// window.location.replace('https://en.wikipedia.org/wiki/' + mw.config.get('wgPageName'));
	            }
	        });
		});
	});
}

var linktext = '<span> || </span><a href="javascript:unknownRollback();" style="font-weight: bold;"><span style="color: black;">[</span><span style="color: blue;">UNKNOWN</span><span style="color: black;">]</span></a>';

$(document).ready(function() {
	if (document.getElementById('mw-diff-otitle1')){
		(async () => {
			await waitForElement(".tw-rollback-link-vandalism");
			document.getElementsByClassName('tw-rollback-link-vandalism')[0].insertAdjacentHTML('afterend', linktext);
		})();
	}
});

// </nowiki>