User:Enterprisey/talk-tab-count.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
This user script seems to have a documentation page at User:Enterprisey/talk-tab-count. |
$( function() {
if( !document.getElementById( "ca-talk" ) ) return;
// Insert count early
var talkTabLink = document.getElementById( "ca-talk" ).childNodes[0].childNodes[0];
talkTabLink.textContent += " (?)";
// Determine the name of this page's associated talk page.
// (If we're already on one, then talkPageName is set to wgPageName.)
// The " | 1" part is to set the 1's place to a 1, which guarantees a talk namespace.
var talkPageNamespace = mw.config.get( "wgFormattedNamespaces" )[ mw.config.get( "wgNamespaceNumber" ) | 1 ];
var talkPageName = talkPageNamespace + ":" + mw.config.get( "wgTitle" );
mw.loader.using( [ "mediawiki.api" ] ).then( function () {
// Get the text of the talk page and count the level-2 headers
( new mw.Api() ).get( {
prop: 'revisions',
rvprop: 'content',
rvlimit: 1,
titles: talkPageName
} ).done( function ( data ) {
if ( !data.query || !data.query.pages ) return;
var pageid = Object.getOwnPropertyNames( data.query.pages )[0],
revisions = data.query.pages[pageid].revisions;
if( revisions === undefined ) {
// The talk page does not exist
talkTabLink.textContent = talkTabLink.textContent.replace( "(?)", "(0)" );
} else {
var text = revisions[0]["*"];
var HEADER_RE = /^\s*==\s*[^=]+?\s*==\s*$/gm;
var headerMatchList = text.match( HEADER_RE );
var headerCount = headerMatchList ? headerMatchList.length : 0;
talkTabLink.textContent = talkTabLink.textContent.replace( "(?)", "(" + headerCount + ")" );
}
} );
} );
} );