User:JSutherland (WMF)/fixingMarkup.js
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
mw.loader.using('mediawiki.util', function () {
$(document).ready(function () {
//create a button the user can click to indicate they want to run this script
//(ganked from https://www.mediawiki.org/wiki/ResourceLoader/Modules#addPortletLink)
var transLink = mw.util.addPortletLink('p-personal', '#', 'Fix Markup', 'pt-fixMarkup');
//what happens when they click it? this!
//(as long as you're in edit mode. If you run it while just viewing a page, nothing happens)
$(transLink).click(function(){
$.ajax( { // Get this URL
url: '/api/rest_v1/page/html/' + mw.util.rawurlencode( mw.config.get( 'wgPageName' )),
// Interpret the result as HTML (as opposed to XML or JSON or something)
dataType: 'html'
} )
.done( function( html ) {
// Parse the result as HTML and put it into a variable called "doc"
var doc = new DOMParser().parseFromString( html, 'text/html' ),
// You can now use jQuery to find stuff using $( 'selector', doc )
// (you have to specify doc because $('p') finds paragraphs on the current page rather than in the parsed text)
$bodies = $('b, i, dd, p, li, dt, di, td, th, h2, h3, h4, caption', doc);
$texts = $bodies.contents().filter(function(){
return this.nodeType === 3; //filters bodies for text nodes (i.e. displayable text, coded as "3") only
//I have no idea what is magical about this combination of .contents().filter etc, though
});
$texts.each(function(){
$(this).replace(/^\:\*/g, "*");
});
$.ajax( { //now to pop the edited wikitext back into the edit window
url:'/api/rest_v1/transform/html/to/wikitext/Main_Page',
method:'POST',
dataType: 'text',
data:{ html: doc.documentElement.outerHTML}
})
.done( function( wikitext ) {
// wikitext is the result of the conversion
$( '#wpTextbox1' ).val( wikitext );
} ); //end the second .done ajax function
} ); //end the first .done ajax function
}); //end click TransLink
});//end document.ready
}); //end mw.loader