Welcome!

XML Authors: Carmen Gonzalez, Dmitriy Stepanov, Nikita Ivanov, Roberto Medrano, Elizabeth White

Blog Feed Post

How to: Use the SharePoint 2013 Client Object Model (SP.js) from a Client Web Part

I was talking to Tom Resing (@resing) last week about using the SharePoint Client Object Model inside a Client Web Part and it became apparent that I left you all hanging with my last post.  I got you to the point where you could build your web part, but referencing SP.js is not as simple as you would think it would be.  I had to look at a lot of code samples to put this all together.  This follow-up post will give you the necessary steps to get started working with SharePoint right away.

The first thing I do is add some script references to the page.  For Client Web Parts, I tend to use a new .js file to host the web part’s JavaScript and I leave app.js to serve the needs of Default.aspx.  Building on my example from the last post, I add a new script called HelloWorldClientWebPart.js.  I add this in the Scripts folder. 

AppHelloWorldScriptProjectItem

We’ll add our code to this file in a minute but first I want to add those references.  In this case, we aren’t loading a reference to SP.js yet.  Instead, we’ll load jQuery from a CDN as well as MicrosoftAjax.js.  You may not need all of those, but chances are you do.

<head>

    <script type="text/javascript" src="../Scripts/jquery-1.6.2.min.js"></script>

    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>

    <script type="text/javascript" src="../Scripts/HelloWorldClientWebPart.js"></script>

</head>

Now we’ll jump over to our new script file.  We’re going to borrow a few lines from App.js starting with variables to hold the context, web, and user.

var context;

var web;

var user;

Now we use jQuery’s document.ready function to add our code.

$(document).ready(

    function () {

    }

);

You can add this line to your document.ready function to get a reference to the SPSite object of the site hosting the client web part (app part) as opposed to the site actually hosting the app itself.  We’ll also need it to get our reference to SP.js as well.

//Get the URI decoded SharePoint site url from the SPHostUrl parameter.

var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

This method relies on getQueryStringParameter which you’ll find in many App examples.

function getQueryStringParameter(urlParameterKey) {

    var params = document.URL.split('?')[1].split('&');

    var strParams = '';

    for (var i = 0; i < params.length; i = i + 1) {

        var singleParam = params[i].split('=');

        if (singleParam[0] == urlParameterKey)

            return decodeURIComponent(singleParam[1]);

    }

}

To get the host URL, you will have to modify your elements.xml to make this work.  Do this by adding {standardtokens} to the URL of the Content element.

<Content Type="html" Src="~appWebUrl/Pages/HelloWorldClientWebPart.aspx?{StandardTokens}" />

When you do this, SharePoint will automatically pass you a number of query string parameters that you can take advantage of including the SPHostUrl.  At that point you can pass the URL into your call to get a SPWeb object.

Back in the JavaScript file, we add the rest of our code.  First we need to get the URL to the 15 folder inside _layouts and assign it to our layoutsRoot variable.  Now we can use the jQuery getScript() method to retrieve the scripts we need.  Before you get SP.js, you have to get SP.Runtime.js.  That is why you see the nested calls below.  Once SP.js can be retrieved, it makes a call to the execOperation method.  This method can then take advantage of the SharePoint Client Object Model.

//Build absolute path to the layouts root with the spHostUrl

var layoutsRoot = spHostUrl + '/_layouts/15/';

 

$.getScript(layoutsRoot + "SP.Runtime.js", function () {

    $.getScript(layoutsRoot + "SP.js", execOperation);

}

);

To demonstrate it’s use, we’ll use the same script example used in App.js.  We start by defining execOperation and getting a reference to the content and SPSite object.

function execOperation() {

    // get context and then username

    context = new SP.ClientContext.get_current();

    web = context.get_web();

 

    getUserName();

}

We then use the same getUserName() and other functions from App.js.

function getUserName() {

    user = web.get_currentUser();

    context.load(user);

    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);

}

 

// This function is executed if the above OM call is successful

// It replaces the content of the 'welcome' element with the user name

function onGetUserNameSuccess() {

    $('#message').text('Hello ' + user.get_title());

}

 

// This function is executed if the above OM call fails

function onGetUserNameFail(sender, args) {

    alert('Failed to get user name. Error:' + args.get_message());

}

Putting the entire script together, here is what it looks like.

var context;

var web;

var user;

 

//Wait for the page to load

$(document).ready(

    function () {

        //Get the URI decoded SharePoint site url from the SPHostUrl parameter.

        var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

 

        //Build absolute path to the layouts root with the spHostUrl

        var layoutsRoot = spHostUrl + '/_layouts/15/';

 

        $.getScript(layoutsRoot + "SP.Runtime.js", function () {

            $.getScript(layoutsRoot + "SP.js", execOperation);

        }

        );

 

        // Function to execute basic operations.

        function execOperation() {

            // get context and then username

            context = new SP.ClientContext.get_current();

            web = context.get_web();

 

            getUserName();

        }

    }

);

 

function getQueryStringParameter(urlParameterKey) {

    var params = document.URL.split('?')[1].split('&');

    var strParams = '';

    for (var i = 0; i < params.length; i = i + 1) {

        var singleParam = params[i].split('=');

        if (singleParam[0] == urlParameterKey)

            return decodeURIComponent(singleParam[1]);

    }

}

 

// This function prepares, loads, and then executes a SharePoint query to get the current users information

function getUserName() {

    user = web.get_currentUser();

    context.load(user);

    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);

}

 

// This function is executed if the above OM call is successful

// It replaces the content of the 'welcome' element with the user name

function onGetUserNameSuccess() {

    $('#message').text('Hello ' + user.get_title());

}

 

// This function is executed if the above OM call fails

function onGetUserNameFail(sender, args) {

    alert('Failed to get user name. Error:' + args.get_message());

}

Lastly, I update HelloWorldClientWebPart.aspx with a div to hold the results.  Here is what the entire file looks like.

<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<WebPartPages:AllowFraming ID="AllowFraming1" runat="server" />

<head>

    <script type="text/javascript" src="../Scripts/jquery-1.6.2.min.js"></script>

    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>

    <script type="text/javascript" src="../Scripts/HelloWorldClientWebPart.js"></script>

</head>

<div>

    <h2>Hello World Client Web Part!</h2>

    <div id="message"></div>

</div>

We can then execute the app in the debugger and then add the App Part to the root page of our developer site.  It should look something like this when you’re done.

AppClientWebPartWithJavaScript

Sorry to leave you hanging like that on my previous blog post.  I hope this helps you get started with your app.  It’s a bit involved but not too bad.  It would be nice to create a custom SharePoint Project Item that does this for us.

Come see my sessions at SPC12 and follow me on twitter @coreyroth.

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is a consultant at Hitachi Consulting specializing in SharePoint and Office 365 for clients in the energy sector. He has more than ten years of experience delivering solutions in the energy, travel, advertising and consumer electronics verticals.

Corey specializes in delivering ECM and search solutions to clients using SharePoint. Corey has always focused on rapid adoption of new Microsoft technologies including Visual Studio 2013, Office 365, and SharePoint.

He is a member of the .NET Mafia (www.dotnetmafia.com) where he blogs about the latest technology and SharePoint. He is dedicated to the community and speaks regularly at user groups and SharePoint Saturdays.

@ThingsExpo Stories
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, discussed how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
The Internet of Things promises to transform businesses (and lives), but navigating the business and technical path to success can be difficult to understand. In his session at @ThingsExpo, Sean Lorenz, Technical Product Manager for Xively at LogMeIn, demonstrated how to approach creating broadly successful connected customer solutions using real world business transformation studies including New England BioLabs and more.
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
There's Big Data, then there's really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. In her session at Big Data Expo®, Hannah Smalltree, Director at Treasure Data, discussed how IoT, Big Data and deployments are processing massive data volumes from wearables, utilities and other machines...
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.