User:Alhadis/global.js

From Meta, a Wikimedia project coordination wiki

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.
/* eslint-env browser */
/**
 * @fileoverview
 *   Redirect mobile-optimised pages to desktop version, unless on mobile.
 *   This is helpful for users whose browsing history is synced across devices,
 *   where browsing Wikipedia on mobile can cause mobile versions of articles to
 *   be listed as history suggestions when typing into the URL bar on desktop.
 */
(function(){
	"use strict";
	
	/**
	 * Return true if the hostname of the specified hostname
	 * matches a recognised MediaWiki domain, and contains a
	 * mobile subdomain named "m".
	 *
	 * @example
	 *    isMobilePage("en.m.wikimedia.org") === true;
	 *    isMobilePage(new URL("http://en.mediawiki.org")) === false;
	 *    isMobilePage() === true; // If running on meta.m.wikpedia.org
	 *
	 * @param {URL|Location|String} [url=window.location]
	 *    Domain name being examined. Defaults to URL of current page.
	 *
	 * @see {@linkcode https://en.wikipedia.org/wiki/Special:UrlShortener|Special:UrlShortener}
	 * @return {Boolean}
	 * @internal
	 */
	function isMobilePage(url){
		if(arguments.length < 1)
			url = window.location;
		url = url instanceof window.Location || url instanceof URL
			? url.hostname
			: String(url);
		var labels = url.split(".");
		switch(labels.slice(-3).join(".")){
			case "m.mediawiki.org":
			case "m.wikibooks.org":
			case "m.wikidata.org":
			case "m.wikifunctions.org":
			case "m.wikimedia.org":
			case "m.wikinews.org":
			case "m.wikipedia.org":
			case "m.wikiquote.org":
			case "m.wikisource.org":
			case "m.wikiversity.org":
			case "m.wikivoyage.org":
			case "m.wiktionary.org":
				return labels.length > 3;
			default:
				return false;
		}
	}
	
	/**
	 * When loading the mobile version of a MediaWiki page
	 * on desktop, automatically redirect to the "correct"
	 * hostname.
	 *
	 * @example "en.m.wikipedia.org" => "en.wikipedia.org"
	 * @returns {Boolean} True if a redirect was triggered
	 * @internal
	 */
	function fixMobileRedirect(){
		if(isMobilePage() && !navigator.maxTouchPoints){
			var labels = location.hostname.split(".");
			var mIndex = labels.lastIndexOf("m");
			if(~mIndex){
				labels.splice(mIndex, 1);
				location.hostname = labels.join(".");
				return true;
			}
		}
		return false;
	}
	
	fixMobileRedirect();
})();