Jump to content

Snippets/Direct imagelinks to Commons

From mediawiki.org
How to use Snippets
List of Snippets
Direct imagelinks to Commons
Language(s): JavaScript
Compatible with: MediaWiki 1.26+ 

Description

[edit]

When you have InstantCommons enabled, by default thumbnails link to a local mirror of the file description page. With this snippet, those anchor links will point directly to Wikimedia Commons.

Code

[edit]
/**
 * Direct imagelinks to Commons
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Direct_imagelinks_to_Commons Revision 2026-04-16
 * @author Krinkle
 */
if ( mw.config.get( 'wgNamespaceNumber', 0 ) >= 0 ) {
	mw.loader.using( [ 'mediawiki.util' ] ).then( function () {
		mw.hook( 'wikipage.content' ).add( function ( $content ) {
			var uploadBaseRe = /^(https:)?\/\/upload\.wikimedia\.org\/wikipedia\/commons/;
			var localFileNSString = mw.config.get( 'wgFormattedNamespaces' )['6'] + ':';
			var server = '(https:)?' + mw.util.escapeRegExp( mw.config.get( 'wgServer' ) );
			var localBasePath = new RegExp( '^(?:' + server + ')?' + mw.util.escapeRegExp(
				mw.util.getUrl( localFileNSString ) )
			);
			var localBaseScript = new RegExp( '^(?:' + server + ')?' + mw.util.escapeRegExp(
				mw.util.wikiScript() + '?title=' + mw.util.wikiUrlencode( localFileNSString )
			) );
			var commonsBasePath = 'https://commons.wikimedia.org/wiki/File:';
			var commonsBaseScript = 'https://commons.wikimedia.org/w/index.php?title=File:';

			$content.find( 'a.image, a.mw-file-description' ).each( function ( i ) {
				if ( uploadBaseRe.test( $( this ).find( 'img' ).attr( 'src' ) ) ) {
					this.href = this.href
						.replace( localBasePath, commonsBasePath )
						.replace( localBaseScript, commonsBaseScript );
				}
			} );
		} );
	} );
}

Notes

[edit]

As of December 2012, installed as gadget (enabled by default) at:

As of January 2014, it was also installed at:

As of July 7th, 2015, it's also in many more places: phab:P896.

See also

[edit]