Jump to content

User:SD0001/skin-pref.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.
// Use timeless skin while on mobile
// Make skin in url persist when links are clicked, useful for testing scripts across different skins
var onMobile = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
var useskin = location.search.match(/useskin=([^&]*)/) && location.search.match(/useskin=([^&]*)/)[1];
if (useskin || onMobile) {

	var skin = useskin || 'timeless';

	// Insert useskin= param into every link
	var fixAnchor = function fixAnchor(a) {
		var href = a.href;
		var baseurl = '', params = '', hash = '';
		var indexOfQ = href.indexOf('?');
		var indexOfH = href.indexOf('#');
		if (indexOfH === -1) {
			indexOfH = undefined;
		}
		if (indexOfQ === -1 || (indexOfH && indexOfQ > indexOfH)) {
			indexOfQ = undefined;
		}

		baseurl = href.slice(0, indexOfQ || indexOfH);
		if (indexOfH) {
			hash = href.slice(indexOfH);
		}
		if (indexOfQ) {
			params = href.slice(indexOfQ, indexOfH);
		}

		if (baseurl && !/(?:&|\?)useskin=/.test(params)) {
			var param = (params ? '&' : '?') + 'useskin=' + skin;
			a.href = hash ? a.href.replace('#', param + '#') : a.href + param;
		}
	};

	// This adds &useskin= param to the destination url on submitting a form
	// Doesn't work for Search and the edit page and many other places
	var fixForm = function fixForm(form) {
		$(form).append(
			$('<input>', { name: 'useskin', value: skin, type: 'hidden' })
		);
	};

	var observer = new MutationObserver(function(mutationsList, observer) {
		for (let mutation of mutationsList) {
			// console.log(mutation);
			//console.log('mutation observed');
			for (let addednode of mutation.addedNodes) {
				// console.log('added node ' + addednode.tagName);
				if (addednode.tagName === 'A') {
					fixAnchor(addednode);
					// console.log('a with id ' + addednode.id + ' fixed');
				} else if (addednode.tagName === 'FORM' &&
					$(addednode).attr('action') &&
					$(addednode).attr('action').startsWith('/w/index.php')) {

					fixForm(addednode);
					// console.log('form with id ' + addednode.id + ' fixed');
				}
			}
		}
	});
	observer.observe(document, { childList: true, subtree: true });

	mw.hook('wikipage.content').add(function() {
		$('a').each(function() {
			fixAnchor(this);
		});

		$("form[action^='/w/index.php']").each(function() {
			fixForm(this);
		});
	});

}