Search code examples
javascriptsharepointsharepoint-2007web-partsclient-side

Get current username on the client side on SharePoint 2007


I need to create a simple static web part - the only dynamic part is the current user login name (needs to be included in a URL parameter in a link).

I'd rather just use a content editor web part instead of a custom web part that I'll need to deploy. In fact, I already did that using JavaScript and ActiveX (WScript.Shell - full code below)

Is there a better, more native way to do it? What I don't like about the ActiveX approach is that it requires more liberal configuration of IE, and even when I enable everything ActiveX-related in the security settings there is still a prompt that needs to be clicked. Cross-browser support is not a major issue, it's intranet - but will be a nice extra, too.

One way I can think of is to scrape the username from the top-right hand corner with jQuery (or just JavaScript), but is there something even cleaner? Or maybe someone has already done the scraping and can share the code to save me some time ;-)

Here's my current solution:

<script language="javascript">
    function GetUserName()
    {
        var wshell = new ActiveXObject("WScript.Shell");
        var username = wshell.ExpandEnvironmentStrings("%USERNAME%");

        var link = document.getElementById('linkId');
        link.href = link.href + username.toUpperCase();
    }
</script>
<P align=center>
    <a id="linkId" onclick="GetUserName();" href="<my_target_URL>?UserID=">open username-based URL</a>
</P>

Solution

  • Include this Web part token in your content editor web part:

    _LogonUser_
    

    It outputs the same value as Request.ServerVariables("LOGON_USER")

    I've done this before including in a hidden span and plain old document.getElementById to get the innertext.