Adding a code snippet to page content on SharePoint 2013

Note: this post is written specifically for SharePoint 2013.

Sometimes it is necessary to add a snippet of code to just one page. Examples could be:

  1. Alternative CSS for just that page, i.e. to style a specific element
  2. Add a snippet of HTML and/or JavaScript, such as for a Google Maps or Youtube embed
  3. Add a piece of CSS to hide the left navigation on specific pages
  4. Add the Open In Explorer Link to a page

There are technically a number of ways to achieve this:

  1. Paste the code directly into the page contents (does not work)
  2. Paste the code into the the HTML source of the Content Editor Web Part (can work, depending on SP version and code)
  3. Use the Embed command  (can work, situational)
  4. Save the code in a text file, save it somewhere on your SharePoint site collection and call the text file via the Content Editor Webpart (my preferred method)

Option #4 is my favorite for a number of good reasons:

  • You can save the code centrally and then call it from multiple places without needing to replicate it
  • By saving it centrally, you only need to update it once if there are changes or updates
  • By saving it in the content database, you can access it from SharePoint Designer or similar, meaning you do not need to keep downloading-updating-uploading
  • It works consistently across all versions of SharePoint from SharePoint 2007 up to Office 365

For this example, I will be using a simple JavaScript which shows copyright information, in this case from 2010 to the current year. This allows the copyright to be kept up to date:

<p>All right reserved  &copy;
<script>
var cur = 2010;
var year = new Date(); 
if(cur == year.getFullYear()) year = year.getFullYear(); 
else year = cur + ' - ' + year.getFullYear(); 
document.write(year);
</script>
</p>

Option 1: Paste the code directly into the page content

You can paste the code directly into the page content.

code-a

However, once you save the page and view it, you will see that SharePoint does not realize that it is code it needs to render in some way.

Conclusion: do not place code directly in the page content as it does not work.

Option 2: Edit source in rich text area / CEWP

In most content editor webparts and all rich text areas, there is a button in the ribbon called “Edit source”. This is great for quick fixes when content has gotten out of hand. In older versions of SharePoint, you could also use it to embed extra code.

Edit Source

You can easily paste your code straight into the Edit HTML window.

However, once you save, SharePoint lets you know that the code that it does not approve of has been stripped.

code3

In this case, some of the embedded code has been stripped out.

code-b

Sometimes SharePoint will strip out all of it and sometimes it will only strip out parts which can cause an odd result. When it doubt, check back into the HTML source to see what has happened with your code and if it is still 100% intact.

Conclusion: while this used to work under some older SharePoint versions, it is generally not a reliable solution for SharePoint 2013.

Option #3: Using the Embed command

SharePoint 2013 includes an Embed command in the ribbon which can be great for adding code snippets to your page:

code4

After clicking the command, you are prompted to insert your code and given a preview:

code-c

SharePoint creates a Script Editor webpart on the page for you. It even includes an “Edit Snippet” button, so you can go back and edit the code later.

code-d

The JavaScript is being displayed correctly in the webpart and also on publishing the page.

Conclusion: in my experience, this works but is dependent on the complexity of the code. Test well before using.

Option 4: save as a text file, call via CEWP

I have saved the JavaScript into a file called copyright.html. The file extension can help SharePoint determine how to parse the code when it is called, but you may need to experiment depending on your code – I have had good results from using txt, html and js extensions in the past.

Here is the file in Notepad++:

code-e

In this demo, I uploaded the HTML file to the document library on the same site as the page we are working with.

code-g

Tip: I tend to use the following rules of thumb as to where to upload these kinds of files:

  1. Think about if you want to save it in the standard Document library, or if you want to create a dedicated document library called “Scripts” or similar
  2. If the file will be called from just one single site, save it on the site
  3. if the file will be used across just one site collection, consider saving it at the root of the site collection or in the Style Library of that site collection (i.e. Styles/Scripts)
  4. If using across multiple site collections, choose the most logical place for it, i.e. on a root site collection

Next, place a Content Editor Web Part (CEWP) on the page and edit the webpart settings. At the top, add the link to the file and click “Apply” to save the changes.

code-h

The content should immediately display in the CEWP on the page.

code-i

Tip: if  you wish to use the same webpart in many places, you could export the configured CEWP and import it as a custom webpart. You can then place it on a page and it will already be configured for you.

Conclusion: this is my favorite method due to the central storage of the files, ease of editing the files and reusability.

23 responses

  1. Great article, im trying to make a shortcut to the open with explorer button with method 3 using the code

    Open with Explorer

    Inside the embed code window it works but when you save it gets converted to

    Open with Explorer

    I was going to try method 4 the reusable method you described but wasnt sure if this would be applicable for what im trying to acheieve

  2. Thank you so much for writing this, Hannah! I love how Microsoft is constantly building in all kinds of ways to edit a SharePoint page but fails in taking into account simple JavaScript. I’m glad you’ve pointed out their epic fails so that it saves us time – when one method doesn’t work, try the other…. Finding just trying to add a function to an anchor tag’s href property is most annoying. It won’t run it if left in the page content, just as you said, and adding it onload through the Embed code makes the function run onload, too – not just onclick. Adding the CEWP and pointing to a text file with the markup and JavaScript made the page freeze (go white) when refreshing. Any other ideas?

    • This isn’t actually junk, in my opinion – it’s a security measure. Admittedly, the behavior has changed a bit from version to version of SharePoint.

      As for why your code isn’t working… the only thing I can think of is to test the code outside of SharePoint in pure HTML. Good luck!

  3. I figured out how to get it working. I needed to save the page down from the Pages library to my local workstation and edit it in Visual Studio (just as easily could’ve edited it in Notepad) and add my external JS library as a reference. Saved it back to the Pages library. Next, I edited the page with SharePoint Designer, said to “Edit in Browser” on the prompt. I went to Insert > Web Part and added the HTML Web Form Part. I added my anchor tag with an href=”myFunction()” that pointed at a function in my external JS file, there, applied the change, and it worked fine. And yeah, I understand how they want to apply security to the Page Content web part, now… just makes it harder for us developers when we now need to use yet another web part on the page to get JavaScript to work. Thanks for your blog and keep fighting the good fight.

  4. Thank you HANNAH for the article.

    I have tried option #3 with embedded web part and it didn’t work for SharePoint 2013. I copied the script from your blog exactly into the snippet editor. It only worked as a code snippet because the tag was html escaped. However when I put actual tag, it worked fine exactly as you described. Just wanted to contribute this subtle point.

    I also subscribed for your blog as I find it very interesting.

  5. Hannah – I have added a script editor with javascript to count up days. The document.write is not displaying the message once I save and close editing of the page. I seems I need to add a get element and something to with inner html but I haven’t a clue – any suggestions?

  6. Hi! I’ve used the content web part for adding a script that sets different background colors for the records in a list (web part). That works when opening the list (the page) because then the content web part is read. However, when sorting or searching in the list the content web part is no longer in action and thereby the background colors disappear. How can I make sure the script is considered also after sorting or searching in the list? Would you know?

    • Hi Martin! My first thought is to wonder if the sorting and filtering are using a different page which doesn’t include the cewp. Beyond that, I’m not sure.

    • None of this has anything to do with the fact you are using web parts. It has to do with the fact you are running the code in $(document).ready(), instead of in its own function, and calling it from $(document).ready(), and from an onclick event you are going to have to attach during $(document).ready() to the titles of your columns (which are what you have to click in order to initiate the filtering, right?). You have to think about this modularly and dynamically — modular, by creating a function to do your events you can call from anywhere instead of placing it directly in the page load function to be called only once, and dynamically, meaning that it has to be able to do what you want “on-the-fly” after the page is already loaded. JavaScript can be made to do all this, but you must add the events during page load to the objects that will initiate the changes. You can’t expect a page to react after it’s loaded if you don’t add event routines to objects that are changing on the page.

  7. Hi. Thanks for replying so fast. The url changes with information related to what column has been sorted etc. By that it’s a different page but there’s no way to edit that page. My thought was to either call the script from the list web part and thereby considered no matter what is done regarding sorting or filtering, or somehow make sure the content web part is considered everytime. None of them seem to work out though.

    • It’s okay if the arguments on the url change, as long as you are still on the same page.

      I’m not sure what your script does, but SharePoint is notorious for not playing well with Javascript. That’s especially true once you start getting into list sorting and filtering.

  8. Yes, it’s a Javascript that I’m using. In short:

    $(document).ready(function(){

    $Text = $(“td .ms-vb2:contains(‘Open’)”);
    $Text.parent().css(“background-color”, “#FF0A0A”);

    $Text = $(“td .ms-vb2:contains(‘Closed’)”);
    $Text.parent().css(“background-color”, “#00FF66”);

    });

    Ok, then I know. Thanks anyway!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s