User:Enterprisey/talk-tab-count.js

$( 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 + ")" ); }       } );    } ); } );