Filling a SharePoint web service gap: Fetching current username, using client-side only jQuery Ajax
I'm stumped as for why no such service was included in the first place, seeing as the code is a one-liner, and I imagine it quite useful to most service clients.
Having first settled on a custom service (code here) to deliver the user name, deploying that isn't always an option. If you've only got client-side access to the portal, you *need* to do it with a script..
So I came up with this solution, which should work in most cases:
window.userInfo =
{
/* Public interface */
getCurrentUsername: function(callback)
{
$.get(
"/_layouts/userdisp.aspx?Force=True",
null,
function(data)
{
var username = window.userInfo._findUsernameFieldText(data);
callback(username);
}, "html");
},
/* Private interface */
_findUsernameFieldText: function(pageData)
{
var fields = $(pageData).find("table.ms-formtable td#SPFieldText");
for(var i = 0; i < fields.length; ++i)
{
field = fields.get(i);
for(node = field.firstChild;
node.nextSibling != null;
node = node.nextSibling)
{
if(node.nodeType == 8 && /FieldInternalName=\"UserName\"/.test(node.nodeValue))
return $(field).text().replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, '');
}
}
return null;
}
};
What I realized, as I pondered this yesterday, is that there are obviously a lot of pages in the portal which lists the current user's info - including the user profile page. Extracting the username should be no harder than asynchronously loading the page (using jQuery) and parsing the resulting form looking for a field commented with 'FieldInternalName="UserName"'.
Should the userdisp page be violently customized, this would be less likely to work, but being a _layouts page; such a customization is unlikely.
Granted the above code, you can test it by pasting that (in a script tag) plus the following into the html source of a content editor web part:
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
google.setOnLoadCallback(function()
{
userInfo.getCurrentUsername(function(usr) { alert("[" + usr + "]"); });
});
</script>
Full source code download here.

0 comments:
Post a Comment