Jump to content

User:Ahecht/Scripts/RedirectID.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.
// RedirectID by Ahecht v0.2.0

$(document).ready( () => {
var titles=[], redirects={};
$( "main#content a.mw-redirect" ).each(function() {
	if (!titles.includes($(this).prop('title'))) titles.push($(this).prop('title'));
});
mw.loader.using( [ 'mediawiki.api' ], () => {
	function getRedirects(titleArr) {
		if (titleArr.length > 0) {
			var fiftyTitles = titleArr.splice(0,50);
			new mw.Api().get( {
				action: 'query', prop: '', redirects: 1, titles: fiftyTitles.join('|')
			} ).fail( (e, f) => console.warn(f.error.info) ).done( data => {
				if (typeof data?.query?.redirects === 'object') {
					data.query.redirects.forEach(i =>
						redirects[i.from] = i.to + (i?.tofragment ? (" § " + i.tofragment) : '')
					);
					getRedirects(titleArr);
				}
			});
		} else if (Object.keys(redirects).length > 0) {
			$( "main#content a.mw-redirect" ).each(function() {
				var title = $(this).prop('title');
				if (typeof redirects[title] === 'string') {
					$(this).prop('title', title + " → " + redirects[title]);
				}
			});
		}
	}
	
	getRedirects(titles);
	
	mw.hook('wikipage.content').add(async function() {
		var newTitles = [];
		$( "main#content a.mw-redirect" ).each(function() {
			var title = $(this).prop('title');
			if (!titles.includes(title)) {
				newTitles.push(title);
				titles.push(title);
			}
		} );
		getRedirects(newTitles);
	} );

} );
} );