Wednesday, November 4, 2015

Get app web and host web title using jQuery promises in SharePoint hosted app

In my previous post, I talked about getting the app web title using jQuery promises. In this post we will talk about how to get the app web as well as host web title using jQuery promises in SharePoint hosted app.

Below is the simple code to get the title of both the web.

 var def = $.Deferred();  
 $(document).ready(function () {  
   var promise = GetHostWebTitle();  
   promise.then(  
     function (hostTitle, appTitle) { $('#message').text("Host web title : " + hostTitle+ ". App web Title : "+ appTitle) },  
     function (result) { $('#message').text("Error :" + result) }  
     );  
 });  
 var appContext;  
 var hostContext;  
 var hostWeb;  
 var appWeb;  
 function GetHostWebTitle() {  
   //Get the host web url from query string  
   var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));  
   //Get context fro host web and app web  
   appContext = SP.ClientContext.get_current();  
   hostContext = new SP.AppContextSite(appContext, hostUrl);  
   //Get the abb web and host web  
   appWeb = appContext.get_web();  
   hostWeb = hostContext.get_web();  
   appContext.load(appWeb, "Title");  
   appContext.load(hostWeb, "Title");  
   appContext.executeQueryAsync(onHostWebSuccess, onHostWebFailed);  
   return def.promise();  
 }  
 function onHostWebSuccess(sender, args) {  
   var hostWebTitle = hostWeb.get_title();  
   var appWebTitle = appWeb.get_title();  
   def.resolve(hostWebTitle, appWebTitle);  
 }  
 function onHostWebFailed(sender, args) {  
   def.reject(args.get_message());  
 }  
 function getQueryStringParameter(paramToRetrieve) {  
   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] == paramToRetrieve)  
       return singleParam[1];  
   }  
 }  

Once you run the above code, you will get the error as Access Denied on host web.












To resolve this issue, make sure you grant read access to the host web using AppManifest file.












Once you granted the access, the output result will show you the host web and app web title.














In the above example we are getting the host web context by using the below line.

 hostContext = new SP.AppContextSite(appContext, hostUrl); 

Also, you can pass multiple parameters when your deferred is resolved. In the above example, I am passing two parameters to the call back function.

 def.resolve(hostWebTitle, appWebTitle);  

3 comments:

  1. is it possible to update the host web title in a SharePoint hosted app then?

    ReplyDelete