« Using SPServices, jQuery and an $8 Tab Plugin to Create a Stunning SharePoint List Visualization | Main | PowerShell - Use an XML File for Script Settings and Logging »
Wednesday
Apr252012

SharePoint and jQuery - Get the Authenticated User's Name and Modify Content Client-Side

Getting the user's name from a SharePoint page and handing off to some client-side code proved messier than I had hoped for.  Part of the problem is that our farm runs on SSL and IE likes to throw the error message when some resources are secure and others are not and the common solution to this (using jquery.SPServices) was falling prone to that error.  Instead I worked around it so we could serve up a custom control on the intranet for someone's 50th birthday and manage it without audiencing controls.

It requires jQuery and the control that contains the username was not always assigned the same ID though it has the same AccessKey attribute so we made do with what we had.

Since this elegant method did not work:
$(document).ready(function() {
	alert($().SPServices.SPGetCurrentUser());
});

we instead went with the following (note that this includes the resulting action). If you are not in an HTTPS environment go with the SPServices option...

<script type="text/javascript">
	$(document).ready(function() {
		var str = '';
		var strContainer = '';
		
		// find the container that contains the user's name (not always the same...)
		if($('#zz14_Menu').attr("accesskey") == 'W') {strContainer = 'zz14_Menu';}
		if($('#zz15_Menu').attr("accesskey") == 'W') {strContainer = 'zz15_Menu';}
		if($('#zz16_Menu').attr("accesskey") == 'W') {strContainer = 'zz16_Menu';}
		if($('#zz17_Menu').attr("accesskey") == 'W') {strContainer = 'zz17_Menu';}
		
		var str = $('#' + strContainer).find("span").text();

		// date driven
		var d = new Date();
		var n = d.getDate();
		if(n==26) // only show on the 26th...
		{
			if(str == 'Jane User')
			{
				$('#mycontrol').attr('src', 'https://server/Rotator/alternative.htm');
			}
		}
	});
</script>

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>