Jump to content

User:Ricordisamoa/CFD.js

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
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.
/*
 * When clicking a link pointing to a CFD subpage from a deleted category,
 * search the page for the corresponding section.
 *
 * @author [[User:Ricordisamoa]]
 */
$( function () {
	if (
		mw.config.get( 'wgNamespaceNumber' ) !== 4 ||
		mw.config.get( 'wgTitle' ).slice( 0, 30 ) !== 'Categories for discussion/Log/' ||
		!document.referrer
	) {
		return;
	}
	mw.loader.using( [ 'mediawiki.RegExp', 'mediawiki.Title', 'mediawiki.Uri' ] ).done( function () {
		var getPageTitle = function ( href ) {
			try {
				href = new mw.Uri( href );
			} catch ( e ) {
				return;
			}

			if ( href.query.hasOwnProperty( 'title' ) ) {
				return href.query.title;
			} else {
				var titleRegex = new RegExp( mw.RegExp.escape( mw.config.get( 'wgArticlePath' ) )
					.replace( '\\$1', '(.+)' ) ),
				matches = titleRegex.exec( href.path );
				return matches ? decodeURIComponent( matches[1] ) : undefined;
			}
		};

		var title = getPageTitle( document.referrer );
		if ( !title ) {
			return;
		}

		title = mw.Title.newFromUserInput( title );
		if ( title && title.getNamespaceId && title.getNamespaceId() === 14 && title.getPrefixedText ) {
			var expectedText = title.getPrefixedText(),
			$anchors = mw.util.$content
			.find( '.mw-headline' )
			.filter( function () {
				return this.hasAttribute( 'id' ) && // a real anchor
					this.children.length === 0 && // with no Element children
					this.childNodes.length === 1 && // but one Node child (we assume Text)
					this.firstChild.textContent === expectedText;
			} );
			if ( $anchors.length === 1 ) {
				window.location.hash = $anchors.first().attr( 'id' );
			}
		}
	} );
} );