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() {
console.log((new Date()).getTime() + " > top of inner func");
// Determine the name of this page's associated talk page.
// (If we're already on one, then talkPageName is set to wgPageName.)
var talkPageNamespaceNum = 2 * Math.floor( mw.config.get( "wgNamespaceNumber" ) / 2 ) + 1;
var talkPageNamespace = mw.config.get( "wgFormattedNamespaces" )[ talkPageNamespaceNum ];
var talkPageName = talkPageNamespace + ":" + mw.config.get( "wgTitle" );
console.log((new Date()).getTime() + " > determined talkPageName");
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 ) {
console.log((new Date()).getTime() + " > top of API callback");
if ( !data.query || !data.query.pages ) return;
var pageid = Object.getOwnPropertyNames( data.query.pages )[0],
revisions = data.query.pages[pageid].revisions;
console.log((new Date()).getTime() + " > got revisions");
// Begin building the count element
var countEl = document.createElement( "span" );
countEl.style.cssText = "padding-top: 1.25em; background: 0; font-size: 0.8em; margin-right: 0.625em";
// Set the text and color based on the talk page's state
if( revisions === undefined ) {
// The talk page does not exist
countEl.style.cssText += "; color: #a55858";
countEl.textContent = "(0)";
} else {
var text = revisions[0]["*"];
var HEADER_RE = /^\s*==\s*[^=]+?\s*==\s*$/gm;
var headerMatchList = text.match( HEADER_RE );
console.log(headerMatchList);
var headerCount = headerMatchList ? headerMatchList.length : 0;
countEl.style.cssText += "; color: blue";
countEl.textContent = "(" + headerCount + ")";
}
// Insert this count into the talk page tab
var talkTab = document.getElementById( "ca-talk" );
talkTab.childNodes[0].appendChild( countEl );
} );
} );
} );