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. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.

/* <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> */