MediaWiki:Common.js

From Phuketer

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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* ABC-WIKIPEDIA-REDLINKS-START */
/**
 * ABC Wiki:
 * Red/missing article links imported from Wikipedia should open Wikipedia,
 * not the local missing-page editor.
 *
 * Local existing pages are untouched.
 */
(function () {
	'use strict';

	function decodeTitle(title) {
		try {
			title = decodeURIComponent(title);
		} catch (e) {}

		return title.replace(/_/g, ' ');
	}

	function titleToWikipediaUrl(title) {
		return 'https://wikipedia.org/wiki/' + encodeURIComponent(title.replace(/ /g, '_'));
	}

	function getMissingArticleTitle(link) {
		var href = link.getAttribute('href') || '';
		var title = null;
		var match;
		var url;

		if (!href) {
			return null;
		}

		/* Format: /w/index.php?title=Thai_Airways_Flight_365&action=edit&redlink=1 */
		try {
			url = new URL(href, window.location.origin);

			if (url.searchParams.get('redlink') === '1') {
				title = url.searchParams.get('title');
			}
		} catch (e) {}

		/* Fallback: catch title manually */
		if (!title) {
			match = href.match(/[?&]title=([^&]+)/);
			if (match && href.indexOf('redlink=1') !== -1) {
				title = match[1];
			}
		}

		if (!title) {
			return null;
		}

		title = decodeTitle(title);

		/* Only normal article titles. Do not send Template:, Module:, File:, Category:, etc. */
		if (title.indexOf(':') !== -1) {
			return null;
		}

		return title;
	}

	function rewriteOne(link) {
		var title = getMissingArticleTitle(link);
		var wikipediaUrl;

		if (!title) {
			return;
		}

		wikipediaUrl = titleToWikipediaUrl(title);

		link.setAttribute('href', wikipediaUrl);
		link.setAttribute('target', '_blank');
		link.setAttribute('rel', 'noopener noreferrer');

		link.classList.remove('new');
		link.classList.add('abc-wikipedia-missing-link');

		link.setAttribute('title', title + ' — opens on Wikipedia in a new tab');
		link.setAttribute('data-abc-wikipedia-title', title);
	}

	function rewriteAllRedlinks() {
		document.querySelectorAll('a.new, a[href*="redlink=1"], a[href*="action=edit"]').forEach(rewriteOne);
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', rewriteAllRedlinks);
	} else {
		rewriteAllRedlinks();
	}

	/* Some skins/modules add or touch content after ready. */
	window.setTimeout(rewriteAllRedlinks, 500);
	window.setTimeout(rewriteAllRedlinks, 1500);

	/* Debug marker: check browser console with window.abcWikipediaRedlinksActive */
	window.abcWikipediaRedlinksActive = true;
}());
/* ABC-WIKIPEDIA-REDLINKS-END */