Blog

SharePoint JavaScript Context Development Part – 2 – SP.ScriptHelpers

5 min read
5 min read

The hidden gem of SharePoint context JavaScript development – SP.ScriptHelpers

This blog is part of the blog series SharePoint JavaScript Context Development

Right firstly I must apologize, I have been away and getting ready for SharePoint Saturday UK, which I have had excellent feedback on my hour-long JavaScript rant over there. Thank you to the whole team for making the day amazing. We managed to raise over £1000 for charity in the name of our departed Dave Colemon, a respected and leading figure in the UK SharePoint community whom we lost earlier this year.

In an IDE far, far away…

…a developer on the ASP.NET AJAX team (Nikhil Kothari) came up with a concept, which he then turned into a tool. The aim was to create JavaScript from a strongly typed language, and the language he chose to do this in was C#. The resulting tool was dubbed Script# and was used for any of the JavaScript files for SharePoint and CRM.

Nikhil’s idea was to create type-safe JavaScript, have true access modifiers, static members, and constants, and apply obfuscation for Private and Internal members.

DING! You may have seen this JavaScript before. It is the code supplied that is full of $v_0 etc. etc. But we have a problem with Script#’s transpiled code. For some reason, anything written in it doesn’t appear on MSDN at documentation.

Definition: Transpiler/Transcompiler convert code through abstract syntax tree transformation, from one language to another with or without extra optimisation.

No matter, we have notepad and can read code. Even though the internal workings of each method are obfuscated slightly, we can infer meaning from the parameters and properties which are referred too.

So let’s dive into another class inside SP.Init.js. 22 Methods, each with no documentation, or internal variables, and nothing really to say what they are intended for. However, they are there in a public namespace, so we can use them. Luckily the naming of these methods found under SP.ScriptHelpers, infers their usage with accuracy. However to ensure we have no confusion I will go through each.

The methods:

  • disableWebpartSelection(context)
    No return value.
    Emulates the mouse up event on web part that is inferred by context.
  • getDocumentQueryPairs()
    Returns a hash set of the current query string variables.
  • getFieldFromSchema(schema, fieldname)
    Iterates through a schema field array, and returns the value of that field. The Schema can be found at ctx.ListSchema, which you may find useful in display templates.
  • getLayoutsPageUrl(pageName, webServerRelativeUrl)
    Converts the values into the stored location of the page in layouts. This is however just a shorthand for SP.Utilities.UrlBuilder.urlCombine(webServerRelativeUrl, ‘_layouts/15/’ + pageName). But this means you don’t have to worry the difference in different SharePoint versions.
  • getListLevelPermissionMask(jsonItem)
    The permissions mask for the current user, provides more information that is required for lists. So if you need just the permission mark for lists, this method will extract the necessary data, providing back a reformatted jsonItem. The value of the permission mask is held in the PermMask property of the object.
  • getTextAreaElementValue(textAreaElement)
    Gets the value of a TextArea Element, it also checks to make sure that it isn’t null or empty. If it is, it will return an empty string instead. This prevents errors when working with TextAreas.
  • getUrlQueryPairs(docUrl)
    Returns a hash set of query string values from a given URL. It provides error checking and conversion for each value.
  • getUserFieldProperty(item, fieldName, propertyName)
    Returns the requested property of a single list item. The item should be the list item from the current context (ctx) this can be useful for display templates.
  • hasPermission(listPermissionMask, listPermission)
    Returns a Boolean value, determining that a given permission mask, has sufficient access to a check permission mask.
  • newGuid()
    Creates a new unique GUID. Very useful for ensuring ID names are unique for example.
  • isNullOrEmptyString(str)
    Same as the Sp.ScriptUtility method shown in the previous blog post.
  • isNullOrUndefined(obj)
    Same as the Sp.ScriptUtility method shown in the previous blog post.
  • isNullOrUndefinedOrEmpty(str)
    Same as the Sp.ScriptUtility method shown in the previous blog post.
  • isUndefined(obj)
    Same as the Sp.ScriptUtility method shown in the previous blog post.
  • replaceOrAddQueryString(url, key, value)
    Returns a newly formatted URL, which either replaces a current query value, or appends the value if it doesn’t exist. The replacement is based on the ‘key’ value given.
  • removeHtml(str)
    Returns a string value, with all HTML tags removed.
  • removeStyleChildren(element)
    Returns a HTML fragment, from a HTML fragment with the all style tags removed.
  • removeHtmlAndTrimStringWithEllipsis(str, maxLength)
    Converts a string with HTML tags, to a short string with an ellipse (…) appended to the end.
  • setTextAreaElementValue(textAreaElement, newValue)
    Sets the value of a target TextArea. Not sure why this exists as it is the equivalent of writing “textAreaElement.value = newValue;”
  • truncateToInt(n)
    Same as the Sp.ScriptUtility method shown in the previous blog post.
  • urlCombine(path1, path2)
    We saw this used earlier to return the layouts path of a file. This method automatically handles the concatenation and ensures the slashes are correctly placed.
  • resizeImageToSquareLength(imgElement, squareLength)
    A nice useful method. This method resizes and crops a target image on the page according to the squareLength provided. It will intelligently resize, and crop the correct direction. However, it also makes the image position relative in order to apply the cropping.

At a glance we have just found 22 methods we can use in display templates, in fact a lot of display templates out there could do with some of these methods being used in order to simplify them.

This is the entire point of using these methods. We use prebuilt and tested methods reducing risk on our code, and we also increase the maintainability and readability of our code for future developers by using built-in methods.

You can look at SP.Utilities on MSDN for more of these helper methods, ensuring your code follows best practices in SharePoint context.

MDS strikes back!

For the next blog post, we will take a look at the Minimal Download Strategy garbage collector and how it all works. We can then start to look for more totally undocumented things in the dark depths of the SharePoint hives JavaScript files that we can use.

Read on Part 3 – Minimal Download Strategy

Subscribe to our newsletter