Friday, June 17, 2016

JavaScript in Sandbox Solutions

Below examples shows deployment of JavaScript files through Sand boxed solution approach. As we know, Sand boxed solutions cant deploy the files to layout directory of SharePoint, I am deploying JavaScript files to Style library and then going to consume in java script code using custom action. Please see the details below.

1. Create a empty SharePoint 2010 or 2013 Empty project with Sand boxed solution selection.

2. Create a module called as 'Scripts' by right clicking on VS project,  I am using module because I will be installing js files in Style library folder of the site.

3. Copy the java script files(jquery-1.8.3.js, jquery-1.8.3.min.js) under scripts also name the Feature appropriately.

Below is the folder structure of application after following the above steps.


In the Element.xml I am going to define the location of JavaScript file location with along Code.txt, The Code.txt contains the required java script that basically displays the site name.

I am using a custom action that would essentially load the 'jquery-1.8.3.min.js' when code.txt starts executing.  Below is how final Element.Xml will look.

[code]<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Scripts" Url="Style Library/Scripts" RootWebOnly="TRUE">
    <File Path="Scripts\jquery-1.8.3.js" Url="jquery-1.8.3.js" Type="GhostableInLibrary"/>
    <File Path="Scripts\jquery-1.8.3.min.js" Url="jquery-1.8.3.min.js" Type="GhostableInLibrary"/>
    <File Path="Scripts\Code.txt" Url="Code.txt" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" /> 
  </Module>
  <CustomAction
  Id="LoadQuery" ScriptSrc="~SiteCollection/Style Library/Scripts/jquery-1.8.3.min.js"
  Location="ScriptLink"
  Sequence="10">
  </CustomAction>
</Elements>
[/code]
Below is final copy of Code.txt file.

[code]<script type = "text/javascript">
    jQuery(document).ready(function() {
    //below code ensure client object is loaded prior to page execution
    ExecuteOrDelayUntilScriptLoaded(initialize,"sp.js");
    });

function initialize(){
    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    context.load(web, "Title");
    context.executeQueryAsync(success,fail);

function success(){
    var message = jQuery("#message");
    message.text("This site is named " + web.get_title());
}

function fail(sender, args){
    alert("Call failed. Error:" + args.get_message());
    }
}

</script>
<div id="message"></div>
[/code]

Once we deploy the solution, I am using a web part to test javascript code.

No comments:

Post a Comment