User:Mike Dillon/Scripts/username.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

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