JavaScript / jQuery on the page at either:
- $(document).ready
- _spBodyOnLoadFunctionNames
will not return the required result, since the menu elements we need to interrogate have not been rendered yet.
Solution:
- Set a timer to keep running a particular function to wait until the menu is rendered
- Stop the timer
- Interrogate the DOM as required using jQuery
Code Example:
1 <script type='text/javascript'>
2
3 var timerHandle = "";
4 var currentWindowsAccount = "";
5 _spBodyOnLoadFunctionNames.push("runCustom");
6
7 function runCustom() {
8 timerHandle = setTimeout(getCurrentLoggedInUser, 10);
9 }
10
11 function getCurrentLoggedInUser() {
12 //Function requires jQuery
13
14 /* Retrieve the current logged in user from the My Profile option in **
15 ** the Welcome Menu (id=ID_MySiteLinksMenu) **
16 ** This needs a timeout to wait for the menu to be rendered via AJAX */
17
18 //Timers are expensive on client resources, clear at all opportunities
19 clearTimeout(timerHandle);
20
21 var welcomeMenuItems = $('#ID_MySiteLinksMenu'); //ie:menu with id='ID_MySiteLinksMenu'
22
23 if (welcomeMenuItems.length > 0) {
24 var onmenuclickValue = welcomeMenuItems.attr("onmenuclick");
25 var onmenuclicksplit = onmenuclickValue.split("=");
26 var loggedInUserString = onmenuclicksplit[1];
27 var loggedInUserStringSplit = loggedInUserString.split("'");
28
29 currentWindowsAccount = loggedInUserStringSplit[0];
30 alert(currentWindowsAccount);
31 }
32 else {
33 //My Profile link has not been rendered yet, try again.
34 timerHandle = setTimeout(getCurrentLoggedInUser, 10);
35 }
36 }
37
38 </script>
No comments: