Insert javascript code within a SharePoint Page as a Web Part

How to insert javascript code within a SharePoint Page as a Web Part. [Without tools like SharePoint Designer].

Without access to Visual Studio or SharePoint Designer, you can still insert code using Javascript into a SharePoint Page using web Parts like content Editor Web Part or Page Viewer WebPart. 

Step 1: Download js files from this link. SPServices is a very useful jQuery library that has many operations like GetListItems[SPList], GetSite[SPWeb]. You can read about it here. If you need SPServices Js file then download using this link. I used jquery-1.4.2.min.js and jquery.SPServices-0.5.6.min.js for most of my coding references.

Step 2: Upload these files into a Doc libraray in a SharePoint Site\Site Collection.

Step 3: In any SharePoint Site, Create a Web Part Page or use an exisiting one. Edit the Page and Insert a Content Editor Web Part. Refer this blog on how to edit a NewForm.aspx. This content editor web part can be used as text editor to insert Code OR Write code in a txt file, Upload into SharePoint and reference its path to this Content Editor Web PArt.





Illustration Simple Code to get and write the Current Site Url in a Web Part.

<html>
<head>
<SCRIPT type=text/javascript src="/mysites/myDocLibrary/JsFiles/jquery-1.4.2.min.js"></SCRIPT>
<SCRIPT type=text/javascript src="/mysites/myDocLibrary/JsFiles/JsFiles/jquery.SPServices-0.5.6.min.js"></SCRIPT>
<SCRIPT type=text/javascript>
      
            var thisSite = $().SPServices.SPGetCurrentSite();
           //alert(thisSite);
            document.write("The Current Site is " + thisSite);

</SCRIPT>
</head>

<Body>

</Body>
</html>

Step 4 : To remove the identity that the code was generated from Content Editor Web Part, within the Web Part Setting, Under Appearance, For Chrome Type select "None". Click OK. Click Apply. Publish the Page.

No comments: