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.
Instead, we need to turn to the ribbon. First, make sure your cursor is inside the text area for the CEWP.
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.
When you drop that down, you’ll see two options. The one we need is “Edit HTML source”.
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.
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):
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:
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.