Monkey Patched Hacking of SharePoint’s UI JavaScript

I need a little break from the JavaScript tutorials, so today I’m going to write something fun you can file under ‘necessity is the mother of invention’. Understand that what follows is not future proof and that it behaves differently in different versions of SharePoint. However, it is mostly the same between SharePoint 2010 and SharePoint 2013…

One of the holes in SharePoint’s JavaScript libraries is the lack of a direct ability to react to a user’s activities related to list items and forms. There are times when you may need to know that a user is viewing or manipulating items without resorting to server-side code. Fortunately, most of the time it is easy to hijack calls to the built-in JavaScript and insert code that does whatever you need. In one of my apps I use this technique to redirect to custom forms. This lets me leverage the stock list views but use custom list forms with no server-side footprint. Note that there are supported alternatives to this technique; you can specify custom forms for a content type via the server and client object models, but I had some special requirements that made those options less than desirable.

Init.js

SharePoint includes a file named init.js that contains a number of interesting functions that can be hijacked via a monkey patch. As you learned in JavaScript for the C# Developer Part 3 – Functions, JavaScript lets you treat functions just like any other type of variable. As a result you can change a function’s implementation by assigning a new function to the original function name. I explained this concept more fully in the post Monkey Patching and SharePoint / Office 365.

Here are the user interface elements and the useful functions they call that I have used this technique to intercept. Be advised that, unfortunately, there are some edge cases, like the infernal calendar view, that do things differently.

  • Edit Item ribbon button – STSNavigateWithCheckoutAlert
  • New Item ribbon button – NewItem2
  • Add link in list views – NewItem2
  • Item links in list views – EditLink2
  • Edit Properties ribbon button in document libraries and edit control block – EditItemWithCheckoutAlert
  • View Properties/View Item ribbon button and edit control block – EditItem2
  • Upload ribbon button in document libraries – EditItem2
  • Add Document link – NewItem2

Demo

Here is an example in a document library view in SharePoint 2013 Preview. I used a content editor web part to contain the following script (http://jsfiddle.net/DougWare/u83LV/).

When I select a document and click Edit Properties an alert displays before executing the original function.

If I view the properties the alert for EditItem2 displays.

 

Be careful with this technique. If you use it, be prepared to change when you upgrade to SharePoint 2016.

–Doug

Author: Doug Ware