Working with SharePoint’s Built-in JavaScript Functions and Properties - Custom SharePoint Solutions with HTML and JavaScript: For SharePoint 2013 and SharePoint Online (2015)

Custom SharePoint Solutions with HTML and JavaScript: For SharePoint 2013 and SharePoint Online (2015)

7. Working with SharePoint’s Built-in JavaScript Functions and Properties

Brandon Atkinson1

(1)

VA, US

When building custom solutions using JavaScript, very often you need help from other libraries to accomplish your efforts. We’ve already seen the power of the jQuery library and how it can help locate HTML elements on our page, update their values, and even make AJAX calls for data. When working with SharePoint, you often need to build URLs, show notifications to users, and more. Luckily, Microsoft provides an enormous amount of JavaScript to assist you with these tasks. I’m not simply talking about the JavaScript Object Model or the REST API. In this chapter, we’ll explore some of the built-in JavaScript functions and properties that are readily available to help you build your custom solutions.

Exploring the JavaScript

SharePoint comes with a long list of built-in JavaScript methods and properties that you can utilize in your code. In fact, the list is so long, it seems quite overwhelming once you dive into it. However, you’ll quickly get used to a handful of them in your day-to-day coding efforts and you can feel at ease knowing there is much more help when it’s needed. Let’s first explore some of the files using Internet Explorer 11’s developer tools. As mentioned earlier in this book, each browser has its own set of developer tools, and each one is slightly different from the other. You can absolutely perform the same tasks in each, but IE11 (and Chrome) show a handy list of available functions once you start typing in the JavaScript console, as shown in Figure 7-1.

A978-1-4842-0544-0_7_Fig1_HTML

Figure 7-1.

Developer tools in IE11. Typing an underscore in the console window will display a list of available JavaScript functions

Open the developer tools in IE11 by pressing F12 on your keyboard. You can also access them via the Settings button in the browser. Click the Console tab, and in the textbox at the bottom, type an underscore. A list will open displaying all the JavaScript functions that begin with an underscore. You can use the arrow keys to move up and down through the list.

Take a few minutes to look through everything you see here. It should give you a nice indication of what is possible using JavaScript with SharePoint. You’ve already seen some of these functions in action; for instance, when using JSLink we utilized the SPClientTemplates functionality to override the web part rendering.

Note

The JavaScript methods and properties available to you are extensive. So much so that there is no way to properly cover it in a single chapter; it would take an entire book. We’ll look at some of the functionality and use it in our example code. You should take some time to fully explore the functions in developer tools and use Google or Bing to track down more information.

_spBodyOnLoadFunctions

The _spBodyOnLoadFunctions is an array that holds a collection of JavaScript functions that should be fired when the page loads. We saw this in Chapter 5 when we needed to wire up a function to fire on page load. The array contains a method named push, where you can pass in the name of a function that should be fired:

_spBodyOnLoadFunctions.push(<FUNCTION_NAME>);

This is an extremely useful function when you do not have access to the jQuery Document.ready() function. There is also an equivalent function called ExecuteOrDelayUntilBodyLoaded, which performs the same task and even has the same signature:

ExecuteOrDelayUntilBodyLoaded(<FUNCTION_NAME>);

_spPageContextInfo

When writing any kind of code, whether JavaScript or something like C#, there are always times when you need to know things about the page, location, or some other environment variable. The _spPageContextInfo object can provide a lot of useful information with ease. In most of the examples in this book, it’s used to provide location information in order to build URLs to request data. At first, this may not seem like terribly important information, but when making REST API calls, or targeting another site via the JavaScript Object Model, it becomes extremely important.

Note

All the properties on the _spPageContextInfo object can be accessed easily in Firebug or in developer tools. Simply open the JavaScript console window and type in each one to see the results for your environment.

_spPageContextInfo.siteAbsoluteUrl

This property provides the absolute URL for the current site collection that the user is in. An absolute URL is a fully qualified URL, which contains the protocol (http:// or https://) and the domain ( www. yoursite .com ). Since SharePoint can utilize Alternate Access Mappings, which allows you to utilize different domains for the same content, this function provides a very useful way to build URLs without worrying about where the user is accessing the page from.

Since this is the path to the site collection, the URL produced could look anything like the following:

· http://www.<DOMAIN>.com

· http://www.<DOMAIN>.com/sites/<SITE_NAME >

_spPageContextInfo.siteServerRelativeUrl

This property provides the server-relative URL for the current site collection that the user is in. A relative URL simply omits the protocol and domain from the URL. This is a handy tool, as there will be many times when you need the relative URL for the site collection. As mentioned, since SharePoint content has the ability to be accessed on many different domains, targeting the relative URL allows you to publish the same code across multiple domains without worrying where the code will be run.

If you were to call this property in the root site collection, for instance, the resulting URL would simply be /.

_spPageContextInfo.webAbsoluteUrl

This property provides the absolute URL for the current web, or site, that the user is in. This is the fully qualified URL that includes the protocol and domain. The URL-produced code looks like the following:

· http://www.<DOMAIN>.com

· http://www.<DOMAIN>.com/<SUBSITE >

· http://www.<DOMAIN>.com/sites/<SITE_COLLECTION>/<SUBSITE >

_spPageContextInfo.webServerRelativeUrl

This property provides the server-relative URL for the current web, or site, that the user is in. As with the site-relative URL, it omits the protocol and domain from the URL. The URL-produced code looks like the following:

· /

· /<SUBSITE>

· /sites/<SITE_COLLECTION>/<SUBSITE>

ExecuteOrDelayUntilScriptLoaded

This function allows you to specify a JavaScript function to delay until another script has been completely loaded. In essence, we’re telling SharePoint: “I want to run this particular function, but I need to wait until this other script has been loaded.” It has the following signature:

ExecuteOrDelayUntilScriptLoaded(<FUNCTION_NAME>, <SCRIPT_FILE>);

SharePoint first checks to see if the specified JavaScript file is loaded; if so, it immediately executes the specified function. If the file has not been loaded, it places the function call into a queue and executes it later. We’ll use this in the next chapter when querying user data using the JavaScript Object Model:

$(function () {

ExecuteOrDelayUntilScriptLoaded(getUserProfileProperties, "sp.userprofiles.js");

});

function getUserProfileProperties() {

var clientContext = new SP.ClientContext();

...

As you can see in this code snippet, we have a jQuery Document.ready() function where we have placed the ExecuteOrDelayUntilScriptLoaded function. We pass in the function getUserProfileProperties and the JavaScript file sp.userprofiles.js. We need to implement this function here, as the code contained in our function can only operate if the sp.userprofiles.js file is loaded. SharePoint provides an easy way to ensure functionality in your code!

Note

The ExecuteOrDelayUntilScriptLoaded functionality is a carryover from SharePoint 2010, where it was located under the SP.SOD object. There are scenarios in SharePoint 2013 where the newer version will not work properly, usually on Publishing Portal pages. If you find that this function is not working, you can revert back to the 2010 implementation. More information can be found at http://msdn.microsoft.com/en-us/library/office/ff408081%28v=office.14%29.aspx .

SP.UI.Notify

The SP.UI.Notify object provides a number of ways to notify the user that something is happening. This functionality provides a way to tap into the out-of-the-box SharePoint notifications and allows your custom solutions to blend seamlessly into the environment. While the examples in this book do not utilize this notification framework, they could easily be refactored to include notifications when a Create or Delete operation is taking place. It’s always a good practice to notify your users of events taking place when you can.

SP.UI.Notify.showLoadingNotification

The SP.UI.Notify.showLoadingNotification function is a quick and easy way to display the familiar “Working on it...” notification. If you’ve used SharePoint for any amount of time, you’ve surely seen one of these messages, which pop out from the right side of the screen. It includes a “spinner” icon, as shown in Figure 7-2.

A978-1-4842-0544-0_7_Fig2_HTML

Figure 7-2.

Loading notification launched via Firebug

You can launch this notification at any time in your code with the following line:

SP.UI.Notify.showLoadingNotification();

In fact, you can also launch Firebug or developer tools and invoke it directly in the browser. Figure 7-2 shows the notification being triggered via Firebug from the console.

This is a quick and handy way to notify the user that something is happening via your code. While this generic notification can certainly suffice in some situations, you may need to provide more explanation about what is going on. For that you can use the SP.UI.Notify.addNotificationmethod.

SP.UI.Notify.addNotification

Much like the previous function, SP.UI.Notify.addNotification is used to display a notification to the user in the same location, but with a custom message. This is perfect when you need to notify the user of an action taking place, but need to be more descriptive than a simple “Working on it...” message. Figure 7-3 shows a custom message being displayed.

A978-1-4842-0544-0_7_Fig3_HTML

Figure 7-3.

A custom message being displayed to notify the user

You can launch this notification with the following line:

SP.UI.Notify.addNotification("Your Custom Message");

As you can see, adding a custom notification couldn’t be easier via JavaScript. There is no maximum length for the message you display. However, as the message gets longer, it eventually hits the other side of the screen and the text begins to wrap. This may not always layout correctly, so it’s best to keep your messages short. Figure 7-4 shows a longer message being displayed.

A978-1-4842-0544-0_7_Fig4_HTML

Figure 7-4.

A longer message can be displayed via a notification

Notifications only remain on the page for about 6 seconds. If you just need to notify the user that an action took place but you do not need to wait for a response, this works just fine. However, sometimes you need to kick off an action and wait for a result. In this case, you may need your notification to stick around a little longer. You can include a Boolean to indicate that the notification should remain by using the following line:

SP.UI.Notify.addNotification("Your Custom Message", true);

By using the preceding line, the notification will remain until it’s manually closed. You can do this by calling the SP.UI.Notify.removeNotification function, passing in the Notification ID from the addNotification function call. When you call the addNotification function, you get back the ID of the notification that was just created, as shown in Figure 7-5.

A978-1-4842-0544-0_7_Fig5_HTML

Figure 7-5.

The Notification ID that is returned when you create a new notification

If we were to use this in code, the line would look like the following:

var notifyId = SP.UI.Notify.addNotification("Hello World", true);

When we execute this line, the notifyId variable now has the ID of the newly created notification. We could later close the notification by using the following line:

SP.UI.Notify.removeNotification(notifyId);

The SP.UI.Notify.removeNotification simply takes the ID of the notification and removes it from the screen. You can also use the Boolean flag when calling the showLoadingNotification function:

SP.UI.Notify.showLoadingNotification(true);

Passing in the Boolean triggers the same return of a notification ID, as shown in Figure 7-6.

A978-1-4842-0544-0_7_Fig6_HTML

Figure 7-6.

A Notification ID is returned when using the Boolean flag

These functions provide an easy way to notify your user of what is going on via JavaScript. If you need to perform a long-running AJAX call, for instance, you can let the user know that this is taking place so that they do not lose patience with your web part.

Summary

Microsoft has gone a long way to not only provide developers with ways to access data via JavaScript, but to also tap into core SharePoint functionality. In this chapter, we explored a small cross section of the built-in JavaScript functions and properties that are available to you. We saw how to access location data to more easily build URLs for REST API calls and hyperlinks. We saw how to load function calls into the body onload event inside SharePoint, as well as how to ensure that functionality is available to our code before it is executed. Finally, we looked at some of the various ways you can notify your users of what your code is doing to provide a better user experience.

© Brandon Atkinson 2015

Brandon AtkinsonCustom SharePoint Solutions with HTML and JavaScript10.1007/978-1-4842-0544-0_8