Create Publishing Page In SharePoint Host Web Using App

Make sure to refer to the js files, given below, in Default.aspx page-

  1. <SharePoint:ScriptLink name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />  
  2.    <SharePoint:ScriptLink name="sp.runtime.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />  
  3.    <script type="text/javascript" src="../_layouts/15/sp.publishing.js"></script>   
In app.js file, add the code, given below- 
  1. //Declare varibales here  
  2.     var currentUser;  
  3.     var appCtxSite;  
  4.     //get Current Context  
  5.     var context = SP.ClientContext.get_current();  
  6. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model  
  7.     $(document).ready(function () {  
  8.         console.log("page loading...");  
  9.         //Get host web URL  
  10.         var hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));  
  11.         var appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));  
  12.         var scriptBase = appWebUrl + "/_layouts/15/";  
  13.         $.getScript(scriptBase + "sp.publishing.js");  
  14.         //get app context using host web url  
  15.         appCtxSite = new SP.AppContextSite(context, hostWebUrl);  
  16.         //Get current user details  
  17.         // getUserName();  
  18.         $("#btnCreate").click(function () {  
  19.             CreatePublishingPage();             
  20.         });  
  21.     });  
  22.   //This method is used to create a publishing page  
  23.     function CreatePublishingPage() {  
  24.         var pageName = "customPage.aspx", pageTitle = "customPage";   
  25.         //get host web using app context site  
  26.         var web = appCtxSite.get_web();  
  27.         //get rootweb folder using hist web  
  28.         var rootFolder = web.get_rootFolder();  
  29.         //get publishing web   
  30.         var pubWeb =new SP.Publishing.PublishingWeb.getPublishingWeb(context, web);  
  31.         //load publishing web and root folder  
  32.         context.load(rootFolder);  
  33.         context.load(pubWeb);  
  34.         //get existing page layout using callback  
  35.         loadPageLayout(function (pageLayoutItem) {  
  36.             console.log("Page Creation is started");  
  37.             var pageInfo = new SP.Publishing.PublishingPageInformation();  
  38.             pageInfo.set_pageLayoutListItem(pageLayoutItem);  
  39.             pageInfo.set_name(pageName);  
  40.             var newPage = pubWeb.addPublishingPage(pageInfo);  
  41.             context.load(newPage);  
  42.             context.executeQueryAsync(function () {  
  43.                 console.log("Page is created successfully");  
  44.                 var listItem = newPage.get_listItem();  
  45.                 context.load(listItem);  
  46.                 context.executeQueryAsync(  
  47.                 // Success callback after getting the actual list item that is  represented by the Publishing Page.We can now get its FieldValues, one of which is its FileLeafRef value.We can then use that value to build the Url to the new page and set the href or our link to that Url.                  
  48.                     function () {  
  49.                         listItem.set_item("Title", pageTitle);  
  50.                         listItem.update();  
  51.                         listItem.get_file().checkIn();  
  52.                         listItem.get_file().publish("Publishing");  
  53.                         var currentPath = "Pages/" + pageName;  
  54.                         //Set custom page as welcome page  
  55.                         rootFolder.set_welcomePage(currentPath);  
  56.                         web.update();  
  57.                         rootFolder.update();  
  58.                         context.executeQueryAsync(function () {  
  59.                             console.log("successfully page is updated as welcome page..")  
  60.                         },  
  61.                         function (sender, args) {                             
  62.                             console.log('Create page failed. ' + args.get_message());                              
  63.                         });  
  64.                     },  
  65.              // Failure callback after getting the actual list item that is represented by the Publishing Page.                    
  66.                function (sender, args) {                     
  67.                    console.log('Get page failed. ' + args.get_message());  
  68.                      
  69.                });  
  70.             },  
  71.             function (sender, args) {                  
  72.                 console.log('Add page failed. ' + args.get_message());  
  73.                 
  74.             });  
  75.         });  
  76.     }  
  77.   
  78. // This function is executed if the above call fails  
  79.     function onfail(sender, args) {  
  80.         alert('Failed to add field in list. Error:' + args.get_message());  
  81.     }  
  82.   
  83.     // this method used split the query string  
  84.     function manageQueryStringParameter(paramToRetrieve) {  
  85.         var params = document.URL.split("?")[1].split("&");  
  86.         var strParams = "";  
  87.         for (var i = 0; i < params.length; i = i + 1) {  
  88.             var singleParam = params[i].split("=");  
  89.             if (singleParam[0] == paramToRetrieve) {  
  90.                 return singleParam[1];  
  91.             }  
  92.         }  
  93.     }  
Note- In appmanifest.xml file, add the permission for the site collection. Finally the page will be created, using an existing template on your host Website.

page

Summary

In this blog, we have explored, how to create a publishing page and set the page as a welcome page, using SharePoint hosted app. Happy coding!! 
Ebook Download
View all
Learn
View all