This post is migrated from previous hosting provider. There are still some issues with old posts. Please make a comment on this post with any issues.

Working with URLs in SharePoint 2010 JavaScripts

Tags: Scripting, SharePoint 2010

The SharePoint 2010 user interface relies heavily on JavaScripts, just take a look at the Ribbon which is completely generated by a bunch of JavaScripts. Often customizations of SharePoint also involve JavaScripts. You need it to open modal dialogs, add notifications, create Ribbon Page Components etc. etc.. JavaScript is just one of the programming languages you must know as a SharePoint developer - and you can do amazing stuff with it (just take a look at SPServices by Marc D Anderson).

SharePoint 2010 JavaScript awesomeness

In SharePoint 2010 the SharePoint product team (finally) spent some time making a nice and decent JavaScript API (not just the ECMAScript Client Object Model stuff). This API contains quite a few nuggets and gems that can be used to simplify the SharePoint JavaScript tasks. Unfortunately they are not well documented if at all, but fortunately they have me to do it for them. In this post I will show you some good scenarios where you can take advantage of using the SharePoint 2010 JavaScript API.

Application Page links

Many SharePoint solutions contains application pages (aka layout pages) that are used for different administrative tasks. A good approach is to open these application pages using the Modal Dialog Framework. To redirect the user to an application page using JavaScript or open a Modal Dialog box with an application page, you need to construct the URL in JavaScript. This is often done using string concatenation using the current site URL and application page URL - but here's a better way:

You can use the SP.Utilities.Utility.getLayoutsPageUrl(pageName) method to get the correct URL to the application page. For instance like this.

var layoutsUrl = SP.Utilities.Utility.getLayoutsPageUrl('DemoPage.aspx');
var options = {
  title: "My Dialog",
  url: layoutsUrl
}
SP.UI.ModalDialog.showModalDialog(options);

Using this method you will always get the correct application page URL to your page in the correct site. If you are using localized versions of the application page there is a localized equivalent of the method called SP.Utilities.Utility.getLocalizedLayoutsPageUrl(pageName) to use.

Concatenating URLs

Once you have the link to your application page you most often need to send parameters to it, such as the current list id or the item id. That's when you start concatenating strings again. Not that difficult, but you need to take care of encoding of the values.

To build URLs you can use the SP.Utilities.UrlBuilder JavaScript object. This object contains quite a few useful methods. First of all it contains three"static" methods:

  • url = SP.Utilities.UrlBuilder.replaceOrAddQueryString(url, key, value): This method takes a URL as input and a query string key-value pair. It either appends the query string key-value pair or replaces the value of an existing key. It returns the modified URL as a string
  • url = SP.Utilities.UrlBuilder.removeQueryString(url, key): This method removes a query string key and value pair from a URL and returns the modified string.
  • url = SP.Utilities.UrlBuilder.urlCombine(url1, url2): Combines the two URLs, making sure that there are no redundant slashes when merging them.

You can also use the UrlBuilder as an object. Take a look at this sample:

   1:  var layoutsUrl = SP.Utilities.Utility.getLayoutsPageUrl('DemoPage.aspx');
   2:  var urlBuilder = new SP.Utilities.UrlBuilder(layoutsUrl);
   3:  var listId = new SP.Guid(SP.ListOperation.Selection.getSelectedList());
   4:  urlBuilder.addKeyValueQueryString('list', listId.toString('B'));                
   5:  var options = {
   6:      title: "My Dialog",
   7:      url: urlBuilder.get_url()
   8:  }
   9:  SP.UI.ModalDialog.showModalDialog(options);

It's the same sample as before but this time we add a parameter to the dialog URL with the currently selected List ID. On line 2) a UrlBuilder object is created from the application page URL. In line 3) I use another SharePoint JavaScript object called SP.Guid, which is very similar to the .NET System.Guid object, to store the currently selected list ID. The list ID is then added to the UrlBuilder object using the addKeyValueQueryString() method, on line 4). This method makes sure that both the key and value are correctly URL encoded. Finally in line 7) the URL is retrieved from the UrlBuilder object.

Note: You must encode Guids when they are formatted with curly brackets. Curly brackets are according the the specification of URLs not allowed. If you're only been developing for IE previously that's not a problem, since IE can handle it anyways But better be safe than sorry...

The UrlBuilder contains the following methods and properties:

  • combinePath(path): appends a path to the UrlBuilder path
  • addKeyValueQueryString(key, value): adds a key-value query string pair to the Url and correctly encodes the key and value
  • get_url() or toString(): returns the URL as a string

With these tools in your hands you should be able to produce safe and correct URLs at all time when building JavaScripts for SharePoint 2010.

12 Comments

  • Christophe said

    Wictor, an important question about these JavaScript libraries: how do you tell the difference between the public methods supported by Microsoft, and the private (?) ones that can be modified without notice in future releases or service packs?

  • Wictor said

    Good question. The JS APIs are very obfuscated and as long as you rely on the ones using "nice names" I think you are good. The OOB JS files relies heavily on these mentioned classes. If you look at the UrlBuilder class in MSDN you'll find that they have removed that info, only a few classes in the SP.Utilities namespace are actually documented. So the question is relevant :)

  • Marc D Anderson said

    Wictor: Thanks for the mention, and good post. This is the sort of stuff I've had to do myself in SPServices and I'm loathe to replace, to keep things working in both 2007 and 2010. At some point, I'm sure I'll fork SPServices so that I can take advantage of these new functions. M.

  • Christophe said

    Wictor, an important question about these JavaScript libraries: how do you tell the difference between the public methods supported by Microsoft, and the private (?) ones that can be modified without notice in future releases or service packs?

  • Jim said

    Great info! You might add a spiff in there about how replaceOrAddQueryString is case sensitive with regards to the key parameter. I got hit on that one...

  • Trackback said

    It's that time of the year, when you're thinking about what you've done and accomplished the last twelve months. I've been writing a summary for the last five years (2006, 2007, 2008, 2009 and 2010) a...

  • David Mann said

    Hey Wictor,

    One thing to be aware of about the urlCombine - it only works when the "extra" slash is on the end of the first parameter. If you look at the definition of the function in SP.init.js you can see why:
    SP.Utilities.UrlBuilder.urlCombine = function SP_Utilities_UrlBuilder$urlCombine(path1, path2) {
    if (path1.endsWith('/')) { <----------------
    return path1 + path2;
    }
    else {
    return path1 + '/' + path2;
    }
    };

    So this will still have redundant slashes:
    var path1 = "www.example.com";
    var path2 = "/someFolder/file.aspx";
    var myPath = SP.Utilities.UrlBuilder.urlCombine(path1, path2);
    //myPath has a value of "www.example.com//someFolder/file.aspx"

    This is in SharePoint 2013, I don't have a 2010 environment handy to test there...

    Dave

  • Daphine Marcelynas said

    Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and everything. Nevertheless think about if you added some great images or videos to give your posts more, "pop"! Your content is excellent but with images and clips, this website could definitely be one of the best in its niche. Amazing blog!

Comments have been disabled for this content.

About Wictor...

Wictor Wilén is the Nordic Digital Workplace Lead working at Avanade. Wictor has achieved the Microsoft Certified Architect (MCA) - SharePoint 2010, Microsoft Certified Solutions Master (MCSM) - SharePoint  and Microsoft Certified Master (MCM) - SharePoint 2010 certifications. He has also been awarded Microsoft Most Valuable Professional (MVP) for seven consecutive years.

And a word from our sponsors...