Jump to content

User:Enterprisey/talk-tab-count.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Enterprisey (talk | contribs) at 21:49, 8 January 2018 (Updating User:Enterprisey/talk-tab-count.js from local version). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
$( function() {
    mw.loader.using( [ "mediawiki.api" ] ).then( function () {

        // Determine the name of this page's associated talk page.
        // (If we're already on one, then talkPageName is set to wgPageName.)
        var talkPageName;
        var currNamespaceNum = mw.config.get( "wgNamespaceNumber" );
        if( currNamespaceNum % 2 === 0 ) {
            talkPageName = mw.config.get( "wgFormattedNamespaces" )[ currNamespaceNum + 1 ] +
                ":" + mw.config.get( "wgTitle" );
        } else {
            talkPageName = mw.config.get( "wgPageName" );
        }

        // 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],
                text = data.query.pages[pageid].revisions[0]["*"];
            var HEADER_RE = /^\s*==(=*)\s*(.+?)\s*\1==\s*$/gm;
            var headerCount = text.match( HEADER_RE ).length;

            // Insert this count into the talk page tab
            var talkTab = document.getElementById( "ca-talk" );
            var countEl = document.createElement( "span" );
            countEl.style.cssText = "color: blue";
            countEl.textContent = headerCount;
            talkTab.childNodes[0].appendChild( countEl );
        } );
    } );
} );