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
 *
 * Required modules: mediawiki.util
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Direct_imagelinks_to_Commons
 * @author Krinkle
 * @version 2022-09-06
 */
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/,
				localFileNSString = mw.config.get( 'wgFormattedNamespaces' )['6'] + ':',
				localBasePath = new RegExp( '^' + mw.util.escapeRegExp( mw.util.getUrl( localFileNSString ) ) ),
				localBaseScript = new RegExp( '^' + mw.util.escapeRegExp(
					mw.util.wikiScript() + '?title=' + mw.util.wikiUrlencode( localFileNSString )
				) ),
				commonsBasePath = 'https://commons.wikimedia.org/wiki/File:',
				commonsBaseScript = 'https://commons.wikimedia.org/w/index.php?title=File:';

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

Notes

[edit]

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

In January 2014, it was also installed at:

On January 19th, 2014, it was installed also at:

It is furthermore included in the following files:

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

See also

[edit]