Adding Script into a Content Editor Web Part (CEWP) in SharePoint 2010

This post was cross-posted on NothingButSharePoint.com on 9 May, 2011.


In my earlier post, I showed how to add script into a page using the CEWP in SharePoint 2007. In this post, I’ll do the same for SharePoint 2010, though in SharePoint 2010 there are other options as well.

It’s worth repeating the intro to the 2007 post:

This one may seem so obvious as to not merit a post or two, but I get questions on it often enough and I realized that if I had posts to refer to, it’d be helpful. I don’t see the CEWP as evil like many people do, though using it can certainly can cause you problems if you use it unwisely. (I generally agree with Andrew about using it on Publishing pages, where script in the CEWP can wreak true havoc.) Assuming you know what you are doing, here are the steps to add script into a CEWP in SharePoint 2007.

The basic idea is the same in SharePoint 2010, however because things have moved into the ribbon the steps are a little different. Christophe Humbert and I have both done posts about this in the past. His was About Scripts, Web Parts and Urban Myths and mine was Script in Content Editor Web Parts (CEWPs) in SharePoint 2010. I’m going to run through the steps here anyway, but you should also take a look at those posts for more info.

Once you’ve added a CEWP to your page, if you open the Tool Pane you’ll see that the “Rich Text Editor…” and the “Source Editor…” buttons are no longer available there.

image

Instead, we need to turn to the ribbon. First, make sure your cursor is inside the text area for the CEWP.

image

Next, look up at the ribbon. The important thing to notice is the HTML dropdown at the right of the Editing Tools tab, Format Text sub-tab.

image

When you drop that down, you’ll see two options. The one we need is “Edit HTML source”.

image

Yup, there’s our favorite white “editor” box again. One would have thought that Microsoft might have improved this UI in 2010, but clearly it wasn’t on the priority list. I’m adding the simplest JavaScript here: just an alert.

image

When you click OK, you’ll see (for a fleeting few seconds), this message in the notification area (by default, the upper right of the page, just below the ribbon container):

image

Read this as “Your HTML source has almost definitely been messed with.” The question is how much, and you’ll just need to check to see. There are undoubtedly some rules around this, but I’m not aware of where they may be documented.

Even with this ridiculously simple JavaScript, the formatting changes a bit:

image

So, while this approach works some of the time, using the Content Link and pointing to script in a file stored somewhere in the Site Collection is a far better way to go. Trust me, it’ll save you headaches. It’s also a better way to manage your scripts and follow good development practices.

Similar Posts

40 Comments

  1. Marc, the List Form Web Part still has a Content Editor box in SP2010. Can’t I use this instead of the CEWP to avoid having Sharepoint mess with my code?

      1. HI
        could you help me to write code to ping IP’s
        172.16.1.2
        192.168.25.5
        10.101.70.4
        through html web part – share point 2010

        Thanks

  2. I just saw a RT of this post and thought I’d comment. I’ve seen lots of scenarios where including code directly in the CEWP is problematic. Like you mentioned Marc, using the Content Link feature is a far better approach. If you’re just using the CEWP as a storage/rendering medium for SPServices all you’ll run into is badly formatted script once SharePoint saves it. That said, if you’re outputting anything from those SPServices calls or other Javascript/jQuery you’ll find that every time you edit the page and save it again, SharePoint will save the script generated markup as part of the DOM. Whatever you outputted becomes part of the permanent page and when your script fires again you’ll end up with duplicate, triplicate, etc. content.

    1. Mike:

      I guess “Assuming you know what you are doing” wasn’t strong enough, eh? The issues you mention will happen predominantly with Publishing pages, but are of concern, for sure. What I wanted to do in the post (mainly) was capture how to add the script so that I could refer people to it. I still prefer adding my scripts into the page itself to avoid some of these issues, but many people use the CEWP approach instead.

      M.

    2. I was having the same problem. If i do any DOM manipulation (for example using something like dataTables, a jQuery plugin), every time the edit page loaded, it would edit the dom and save the edited dom on page save.

      I worked around this issue by only running the script if SharePoint was in browse mode. you can detect browse mode with something like this:

      if ($(‘input[name=”MSOSPWebPartManager_DisplayModeName”]’).val() == “Browse”){
      //edit DOM
      };

      hope this helps.

  3. Is it necessary to go the CEWP route in SharePoint 2010? In WSS 3.0, I use SharePoint Designer to put script tags at the end of the PlaceHolderMain asp:content section. This drops them towards the end of the content, although not at the very end like I would like. Does that still work in SharePoint 2010?

    1. CarlosT:

      I usually put my script tags just after this line:

      <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

      I find that works consistently. In most cases these days, I’m using jQuery with $(document).ready, so where my script goes in the page is less important.

      M.

  4. I’m having a problem where after I add a CEWP and either put my tag code in the source directly, or reference the code in an external file using the content link, when I leave editing mode, the ‘List Tools’ ribbon goes away. The only way to get it back is to remove the CEWP.

    Why would I be losing that in the ribbon?

    1. Never mind. New to 2010 … ‘really’ new :)

      If someone else ‘really’ new stumbles upon this having the same concerns as me, the reason it goes away is if the first web part on the page is not the list (for example) and is your CEWP, then the List Tools ribbon won’t show. If you click on the list web part below to select it, the ribbon shows up.

      Which I guess raises an interesting question: Can you select the 2nd web part to have ‘focus’ when a page loads? Now that I understand what the issue is, I get it, but it wasn’t terribly intuitive.

  5. Hi Mark,

    Thanks for the post. I just followed the post and added the content editor web part in one of the sharepoint library(AllItems.aspx). After adding this webpart, I am not able to see complete ribbon control. Before adding the webpart I was able to see this. Please let me know is this is a known issue or do I need to change any thing.

    1. It’s hard to dsay why you aren’t seeing the ribbon without knowing what you are trying to with your script and seeing it. Odds are you’ve done something that breaks the ribbon.

      M.

  6. Hi Marc,

    I want to add a color picker and a rich text editor in web part configuration using editor part(sharepoint 2010). Can you please guide me how can I start this. Is it possible to add a ajax color picker or a js color picker in configuration part using editor part. And how can I add a new rich text editor (Or just use the rich text editing option of sharepoint 2010 ribbon).

    Thanks
    Shuvo

    1. Shuvo:

      You can certainly do this, but keep in mind that this approach means that you will have to add the CEWP to every form page where you want to alter the behavior. You might want to look at a third party editor like Telerik’s RADEditor or the like if you want the capability to be more widely available.

      M.

  7. Hi Marc,

    Do you know of a way that I can run some javascript AFTER a new form loads? What I’m trying to achieve is the following: When a user is within the context of an item that belongs to a list – listA – and they are trying to create a new instance of a different list – listB – and they click on a ‘add a new item’ for listB, the new item form should prepopulate the name of the item from listA in the new form of listB since it’s within the context already. And they are internally related.

    The inner details I suppose aren’t relevant, I just need to know if it’s possible to prepopulate this new form toolbar AFTER the new form completely loads.

    I’m not sure if this should be done via custom actions (for the list instance) or javascript, or a combination of both.

    At this point, I’ve played around with the _spBodyOnLoadFunctionNames.push(“fillDefaultVAlues”); function, but to no avail.

    Any suggestions?

    -Elias

    1. Elias:

      SharePoint gives you the
      _spBodyOnLoadFunctionNames function so that you can run your script with the assurance that the page is fully loaded.

      With jQuery, you can use $(document).ready(), which accomplishes basically the same thing.

      You may not need either method; it all depends on what your script is doing.

      As for the prepopulating thing, I like to pass values on the Query String. You can grab those values with script and populate whatever columns you like.

      M.

  8. I have to add a comment tag in ribbon menu edit html source editor without CEWP , but i am able to put after saving the page that comment tag is not appearing in html source.

    Please help me out from this issue.

    Would be great in advance

    Thanks
    Varma

    1. Varna:

      I really don’t understand what you’re trying to do, but generally for ribbon customization, I’d think you’d need to turn to managed code.

      M.

  9. ${ Title }

    $(document).ready(function () {
    // Get the list data.
    $.getJSON(
    ‘../_vti_bin/ListData.svc/Posts?$top=5’,
    function(data) {
    $(‘#postsTemplate’)
    // Select the template.
    .tmpl(data.d.results)
    // Bind it to the data.
    .appendTo(‘#postsContainer’); }
    // Render the output.
    );
    });

    I’m using the above code in the above mentioned HTML source editor and expecting the First 5 records to be displayed. But I don get a output. But if i use an alert to just test as you have said it works. how might be the problem

    1. My guess is that your selector for the container where you want to put the content is incorrect. If you’re seeing data in your alter, then you should do some debugging.

      M.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.