Javascript examples

From Linkwiki
tbd @

Background

It is possible to define JavaScript directly in wiki pages. Depending on what page it is, the JavaScript will then be loaded for some group of users.

If Extension:Gadgets is installed, these examples can also be made into a gadget, to be loaded only if a user enables it.

Hilfe:JavaScript lists all the possible pages where JavaScript can be defined in Wiki Aventurica.

Actually in use are the following pages:

Wikipedia:User scripts links to many examples of user scripts.

Basics

When making adjustments with JavaScript, you should remember that users could have deactivated JavaScript in their brower configuration.

If you decide to use JavaScript, knowing jQuery will probably simplify the code. Tasks typical for MediaWiki can also be done by using MediaWiki functions.

Manual
Manual:Interface/JavaScript
Documentation
javascript, jQuery, MediaWiki
Selection of elements
by id: "#element"
by class: ".element"
Validator
jslint.com
Debugging
console.log( "Test1" );

The following code was published on the MediaWiki email list by User:Brion Vibber and User:Krinkle, respectively, as an answer to how JavaScript functions should be implemented:

// If we haven't already started loading the module, start loading it:
mw.loader.using('mediawiki.util', function() {
  // Module is loaded, *but* it's possible the page HTML is not done. Wait
for it:
  $( function() {
    // Now it should be safe to do everything:
    mw.util.addPortletLink(....);
  } );
});
$.when(
  $.ready,
  mw.loader.using( [ 'mediawiki.util' ] )
).then(function(){
  // mw.util.addPortletLink( ... );
} );

Gadgets

Here is a list of gadgets we have been using at Wiki Aventurica:

Examples

automatic expansion of all grouped changes in Special:RecentChanges

// Auto-Expand all grouped RC/Watchlist entries.
$(function() {
  $('.mw-enhancedchanges-arrow').click();
});

TOC collapsed by default

The table of contents takes up quite some space, better to have it collapsed by default.

used methods
used in
MediaWiki:Common.js
/**
 * collapses TOC by default
 *
 * @version 31.03.2020
 * @author [[wde:StipenTreublatt]]
 */
$(window).ready(function() { $('.toctogglecheckbox').click(); });

Search focus on main page

When loading the main page of a wiki, people might be looking to search for a page. This function automatically focuses the search bar when loading the main page, saving the users a click.

used methods
used in
MediaWiki:Common.js
/**
 * when loading the main page, focuses the search bar
 *
 * @source https://en.wikipedia.org/wiki/MediaWiki:Gadget-searchFocus.js
 * @version 12.11.2013
 * @author [[wpen:User:Nihiltres]], [[wpen:Krinkle]]
 */
if ( mw.config.get( 'wgIsMainPage' ) ) {
  $( function () {
    $( '#searchInput' ).focus();
  } );
}

In my opinion, the link to Special:Upload (only available to users who are logged in anyways) should be amoung the personal links.

used methods
used in
MediaWiki:Group-user.js
/**
 * move upload link to personal links
 *
 * @version 28.09.2015
 * @author [[wde:StipenTreublatt]]
 */
$( "#pt-mycontris" ).after( $( "#t-upload" ) );

confirmation for rollback

This prevents accidental rollbacks by sysops.

used in
MediaWiki:Common.js
/**
 * requires confirmation for rollback action
 *
 * @source https://en.wikipedia.org/wiki/User:MusikAnimal/confirmationRollback.js
 * @version 30.04.2017
 * @author [[wpen:User:MusikAnimal]]
 */
$.when( mw.loader.using( ['mediawiki.util'] ), $.ready).then( function() {
	$(".mw-rollback-link").on('click', function(e) {
		var count = e.target.innerText.match(/\d/) ? e.target.innerText.match(/\d+/)[0] : null,
			message = 'Rollback ' + (count ? count + ' edits' : 'edit') + ' by ' + mw.util.getParamValue('from',e.target.href) + '?';
		if(!confirm(message)) return e.preventDefault();
	});
}());

This function adds a "sandbox" link to the personal links. This could also be achieved via the Extension:SandboxLink.

used methods
mw.util.getUrl, mw.util.addPortletLink
parameters
  • first parameter: To which "portlet" the link will be added, in this case 'p-personal'.
  • second parameter: URL to which the link will point to, in this case the subpage "sandbox" of the current user.
  • third parameter: The text displayed by the link, in this case "My Sandbox".
  • fourth parameter: ID of the link in the html code, in this case 'pt-mysandbox'
  • fifth parameter: Tooltip for the link, in this case "My little Sandbox"
  • sixth parameter: Accesskey, or null
  • seventh parameter: ID of the link, after which the new link will be inserted, in this case '#pt-mytalk'. If none given, the link will be added after the last existing one.
Used in
MediaWiki:Group-user.js
/**
 * Add a "My sandbox" link to the personal portlet menu.
 *
 * Required modules: mediawiki.util
 *
 * @source https://www.mediawiki.org/wiki/Snippets/MySandbox
 * @version 12.10.2026, adapted for Wiki Aventurica
 */

$( function () {
	var conf, params, title, url;

	// Customize/Translate this to your needs
	conf = {
		subpageName: 'Sandkasten',
		portletLabel: 'Sandkasten',
		portletTooltip: 'Persönliche Seite zum Experimentieren'
	};
	// Don't alter the code below

	params = {
		action: 'edit',
		redlink: 1
	};

	title = 'Special:MyPage/' + conf.subpageName;

	url = mw.util.getUrl( title, params );

	mw.util.addPortletLink(
		'p-personal',
		url,
		conf.portletLabel,
		'pt-mysandbox',
		conf.portletTooltip,
		null,
		'#pt-preferences'
	);
});

This function adds a purge link to the page tools, giving users the option to refresh the server cache of the page with one click. This function should not work for bots, see Manual:Purge.

used methods
used in
MediaWiki:Common.js
/**
 * adds purge link to page tools
 *
 * Dependencies: mediawiki.util, mediawiki.api
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Purge_action
 * @version 04.04.2020
 */
$.when( mw.loader.using( [ 'mediawiki.util', 'mediawiki.api' ] ), $.ready ).then( function () {
	if ( $( '#ca-purge' ).length || mw.config.get( 'wgNamespaceNumber' ) < 0 ) return;
	var node = mw.util.addPortletLink(
		'p-cactions',
		mw.util.getUrl( null, { action: 'purge' } ),
		'Purge',
		'ca-purge',
		'Purge the server cache of this page'
	);
	$( node ).on( 'click', function ( e ) {
		new mw.Api().post( { action: 'purge', titles: mw.config.get( 'wgPageName' ) } ).then( function () {
			location.reload();
		}, function () {
			mw.notify( 'Purge failed', { type: 'error' } );
		} );
		e.preventDefault();
	} );
} );

Adds "delete" and "history" links to the pages linked in Special:WhatLinksHere.

used in
MediaWiki:Common.js
/**
 * Adds "hist" and "delete" link to [[Special:WhatLinksHere]]
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Special:WhatLinksHere_action_links
 * @version 03.04.2018, adapted for Wiki Aventurica
 */
$( '#mw-whatlinkshere-list li' ).each( function() {
  var url = mw.config.get( 'wgScript' ) + '?title=' + encodeURIComponent( $( 'a:first', this ).text() ) + '&action=';
  //if #ca-delete exists, user should be allowed to delete
  if ($( "#ca-delete" ).length) {
    $( '.mw-whatlinkshere-tools a:last', this ).after( $( '<a>' ).attr( 'href', url + 'delete' ).text( 'delete' ) ).after( ' | ' );
  }
  $( '.mw-whatlinkshere-tools a:last', this )
    .after( $( '<a>' ).attr( 'href', url + 'history' ).text( 'history' ) ).after( ' | ' );
});

The lists on Special:AllPages and Special:PrefixIndex are displayed in three columns, which can be confusing. This script combines the three columns into one, numbering the items in the process. It also numbers the list on Special:Whatlinkshere.

used methods
used in
Gadget-OneColumn.js
code
/OneColumn

customization of edit toolbar

This function customizes the edit toolbar, see the manual at Extension:WikiEditor/Toolbar_customization.

The signature button could also be controlled by $wgExtraSignatureNamespaces.

used in
MediaWiki:Common.js
code
/ToolbarCustomization

defaultsummaries

This function adds selection boxes for default edit summaries.

code
/DefaultSummaries

These two functions create two rows with links and information beneath the user name on user pages:

  1. userlinks: Adds a row with links to special pages containing information in regard to the user account; if these links exist by default somewhere else in the UI, they are moved.
  2. userinfo: Adds a row with information about the user groups, the number of edits, and the age of the user account.
used methods
used in
MediaWiki:Common.js
code
/Userlinks and Userinfos

hide sidebar while editing

This function hides any sidebar while the user is editing a page.

used in
MediaWiki:Gadget-ExpandEdit.js
/**
 * Hide sidebar while editing
 * 
 * @source https://en.wikipedia.org/wiki/User:Zellfaze/expandEdit.js
 * @author [[wpen:User:Zellfaze]] on https://en.wikipedia.org/
 * @version 30.09.2015, adapted for Wiki Aventurica
 */

if (jQuery('#wpTextbox1').length) {
  if ( mw.config.get( 'skin' ) === 'monobook' ) {
    jQuery('#p-search').css('display', 'none');
  }
  jQuery('#panel').css('display', 'none');
  jQuery('#mw-panel').css('display', 'none');
  jQuery('#p-logo').css('display', 'none');
  jQuery('#content').css('margin-left', '0px');
  jQuery('#mw-head-base').css('margin-left', '0px');
  jQuery('#left-navigation').css('margin-left', '0px');
}

better diffs

This function cleans up diffs by removing markings of content which was not changed.

used in
MediaWiki:Gadget-CleanDiff.js
code
/CleanDiff

This function adds the day of the week on Special:RecentChanges and Special:Watchlist.

used in
MediaWiki:Gadget-Wochentag.js
code
/Weekday

This function adds a live clock at the end of the personal links.

used in
MediaWiki:Gadget-UTCLiveClock.js
code
/LiveClock

This function adds some toolbox links useful for debugging.

used in
MediaWiki:Gadget-DebugLinks.js
/**
 * Add a toolbox link to display the current page with MediaWiki message names replacing their text
 * Add a toolbox link to reload the current page with debug mode enabled
 * 
 * @source [[wpen:MediaWiki:Gadget-ShowMessageNames.js]] and [[wpen:MediaWiki:Gadget-DebugMode.js]]
 * @version 05.04.2018
 * @author [[wpen:User:Edokter]] on https://en.wikipedia.org/
 */
 
mw.loader.using( 'mediawiki.util' ).then( function () {
  mw.util.addPortletLink(
    'p-pagemisc',
    location.href.replace( location.hash, '' ) + ( location.search ? '&' : '?' ) + 'uselang=qqx',
    'Systemmeldungen',
    't-messagenames',
    'Shows the names of the system messages used on this page'
  );
  mw.util.addPortletLink(
    'p-pagemisc',
    location.href.replace( location.hash, '' ) + ( location.search ? '&' : '?' ) + 'debug=true',
    'Debug-Modus',
    't-debugmode',
    'Loads the current page in debug mode'
  );
});

show page creation stats

This function reads page creation stats from the html code of the current page.

used in
MediaWiki:Gadget-ShowPageStats.js
/**
 * Simple script to scrape a page's html comments (looking for 'served by', 'newpp' and 'Transclusion expansion time report').
 * 
 * @source https://en.wikipedia.org/wiki/User:Splarka/showcomments.js
 * @version 20.05.2024, adapted for Wiki Aventurica
 * @author [[wpen:User:Splarka]] on https://en.wikipedia.org
*/

$(function() {
  mw.util.addPortletLink('p-pagemisc','#','Seitenerstellungs-Statistik','t-sps');
  $("#t-sps").on("click", function(){
      alert(dumpComments(document.getElementsByTagName("body")[0]));
  });
})

function dumpComments(obj) {
  var childs = 0; var txt = '';
  if(obj.nodeType == 8 && obj.nodeValue.search(/(NewPP|Served by|Transclusion expansion time report)/) != -1) { 
    txt += obj.nodeValue;
  }
  while(obj.childNodes[childs]) {
    txt += dumpComments(obj.childNodes[childs]);
    childs++;
  }
  return txt;
}

remove elements from pages

This removes the first element of the infobox (in Wiki Aventurica a line repeating the page title) and the heading "Kurzbeschreibung" (in Wiki Aventurica, different to Wikipedia, containing the first block of text).

used methods
used in
MediaWiki:Gadget-MinimalDesign.js
$( "table.infobox" ).find( "tr" ).filter( ":first" ).remove(); //Überschrift der Infoboxen entfernen
$( "#Kurzbeschreibung" ).parent().remove(); //Überschrift "Kurzbeschreibung" entfernen