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,

    Wouldn’t it actually be easier to just place all the script in a text document, upload it to SP, and then have the CEWP point to it?

    – Mark

    1. Mark:

      That’s what I usually do these days. I’ll have a txt document which pulls in the .js and .css files I need in the page. There are times when you just want to add a quick snippet of script and putting it inline is just easier. Note that I recommend the txt file approach at the bottom of the post, but it may be getting lost.

      M.

  2. Hi Marc,

    I created a .txt file with the coding below to keep my calendar expanded, uploaded it to SharePoint 2007, then used the Content Link to the text file in the CEWP below my calendar web part however, now the top link bar is not working. Am I missing something. Thanks, Robin

    var yScroll = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;var y = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;var xScroll = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;var x = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;var cover = document.getElementById(“cover”);cover.style.height = (y + yScroll) + “px”;cover.style.width = (x + xScroll) + “px”;function expand() {if (document.referrer != location.href && !location.href.match(/CalendarPeriod=((week)|(day))/i)) { GetMonthView(‘11111111’); }else { cover.style.display = “none”; }}window.onload = function() { expand(); };

  3. Marc,

    I’ve got a situation where wss 3.0 site just will not run the javascript in the CEWP, whether placed in Source editor or linked to text file. It is something security oriented because it is not working on our Corp wss 3.0 install but works fine on our local server wss 3.0 install. I did wss 3.0 install on both and have access to Central Admin and servers, they should be identical.

    Are you aware of any security feature that would disable javascript from running on server side? Or something on browser client which would react to javascript differently just because of site location? You can see in View Source but it does not run in any browser, IE, Chrome or Firefox.

  4. Never mind, issue solved. The javascript I copied in had extra single quotes which basically made page treat as a comment. That is why debuggers didn’t see it, made it appear like not running. Because as comment, it wasn’t. Duh.

  5. i don’t make sure my post appear so i posted it again
    i needs to code to ping 3 ip
    through the web part [ html part ]
    i am beginner for that

    1. Ayman:

      I’ve never built a “ping” functionality before, but you could use the .ajax() function, I suppose. If there’s a reply, good, if not, bad.

      M.

  6. Hi Mark,
    Thank you for your post. I am trying to add a script to the newForm.aspx of a survey. I am not able to get the upper ribbon where the HTML edit option. I can see it when creating a new page in sharepoint designer. The problem is that I need to have it in the default newForm.aspx of the survey. Do you know how can I add the script in the newform of a survey? Thanks.

      1. I am using SharePoint 2010, and I am doing it through sharepoint interface, not SPD. I am able to see the upper ribbon (Browse, Page, Editing Tools, Web Part Tools) when click on edit page of newform.aspx in Custom list. The problem is that with the newform.aspx of a Survey, the upper ribbon do not get displayed, I am able to add web parts but I cannot access any ribbon options. Do you know if this is a bug or any workarround?

        1. Mary:

          The ribbon always shows you options based on the current context. If you have dialogs enabled (and I think there’s a bug with surveys where you can’t turn them off) then you only see the ribbon options which apply to creating survey items (responses).

          M.

  7. Hi Mark,

    Is there any way to send data from another web part to the Content Editor Web Part. I know the CEWP does not accept connections, but I’m thinking there has to be a way, possibly using script, to grab data from another web part on the page. Any ideas?

    Thanks!

    1. Paulette:

      You can’t “send data” to the CEWP, but if you have script in the CEWP, it can parse anything out of the page that is there. That will happen client side, of course.

      M.

  8. Marc,
    I want to make insert pictures in several questions of my survey. I have started creating text files with the Javascript, but I was wondering if it was possible to have only one text file?
    What is the correct coding in Javascript to separate the different “commands”?

    Thanks a lot!
    Isabelle

  9. ya its good. but i want to fetch list data using jquery following code

    Loading…

    ExecuteOrDelayUntilScriptLoaded(loadSharePointPictures, 'sp.js');
    
    
    
    function loadSharePointPictures() {
        //fetch the list of items using the client object model
        var context = new SP.ClientContext.getcurrent();
        //get the current website
        var web = context.getweb();
        //get the pictures list
        var list = web.get_lists().getByTitle('Images1');
        //create the query to get all items
        var query = SP.CamlQuery.createAllItemsQuery();
        //get all items from the query
        pictures = list.getItems(query);
        //load the context
        context.load(pictures, 'Include(FileLeafRef,FileDirRef)');
        //execute the query in async mode
        context.executeQueryAsync(
            Function.createDelegate(this, this.success), 
            Function.createDelegate(this, this.failed));
    }
    
    
    
    function success(sender, args) {
        pictureArray = new Array();
        var pictureCount = 0;
        var enumerator = this.pictures.getEnumerator();
        while(enumerator.moveNext()) {
            var currentItem = enumerator.getcurrent();
            var filename = currentItem.getitem('FileLeafRef');
            filename = filename.replace('.', '');
            filename += '.jpg';
            var dir = currentItem.getitem('FileDirRef');
            filename = dir + '/_t/' + filename;
            pictureArray[pictureCount++] = filename;
        }
        var newHtml = '';
        for(i=0; i<this.pictureArray.length; i++) {
            newHtml += '';
        }
    
    
    
    $('#pictureMicroGallery').html(newHtml);
    
    
    }
    
    
    
    function failed(sender, args) {
        $('#pictureMicroGallery').html(args.get_message());
    }
    

    like this so how it should be.
    and another way also there like from Site Assets creating text file and call it into content editor but from this way also not find outing the sp list. all path and syntax is proper in sp2010.

    if you know any idea let me know. and also remplya me on sudarshan00live.com

    1. Sudarshan:

      You haven’t said what the issue is, so I’m not sure what to tell you. The easiest way to work on code like this is to store your script in a .js file, reference that .js file in an HTML file using a script tag, and load the HTML file in the Content Link in the CEWP.

      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.