User:Mike Dillon/Scripts/username.js

From Wikipedia, the free encyclopedia
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.
/* <pre><nowiki> */

/**
 * Gets the name of the user associated with the current page. This works for user pages, user talk pages,
 * subpages of user and user talk pages, and the Special:Contributions page.
 *
 * If you want the name of the user who is viewing the page, use the wgUserName variable.
 *
 * If the current page is not associated with a user, then a null value is returned.
 *
 * NOTE: This function relies on page naming conventions and will return a user name for appropriately
 * titled pages regardless of whether the user in question actually exists.
 */
function getUsernameForCurrentPage() {
    try {
        if (wgCanonicalSpecialPageName == "Contributions") {
            // Find the form containing the element with the id "namespace"
            var form = document.getElementById("namespace").form;

            // Extract the username from the "target" field of the form
            return form.target.value.replace("_", " ");
        } else if (wgNamespaceNumber == 2 || wgNamespaceNumber == 3) {
            return wgTitle.split('/')[0];
        }
    } catch (e) {
        // Fall through
    }

    return null;
}

/* </nowiki></pre> */