Question

I've been looking for a way to add a web part to a page using JSOM/CSOM or any other api available to sharepoint hosted apps.

The only solutions I have found so far are for custom sharepoint solutions. Could anyone confirm that this is (im)possible?

To be clear, I want to add a web part to a sharepoint page. Not to a page of my app.

Was it helpful?

Solution

How to add WebPart client object on page via JSOM

function addWebPart(webUrl, pageUrl,webPartXml,zoneId,zoneIndex, Success,Error){
    var context = new SP.ClientContext(webUrl);
    var web = context.get_web();

    var file = web.getFileByServerRelativeUrl(webUrl + pageUrl);
    var webPartMngr = file.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    var webPartDef = webPartMngr.importWebPart(webPartXml);
    var webPart = webPartDef.get_webPart();
    webPartMngr.addWebPart(webPart, zoneId, zoneIndex);

    context.load(webPart);
    context.executeQueryAsync(
      function() {
        Success(webPart);
      },
      Error
    );
}

Example: add Content Editor on root web

var webPartXml = '<?xml version="1.0" encoding="utf-8"?>' +
'<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">' +
    '<Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>' + 
    '<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' + 
    '<Title>$Resources:core,ContentEditorWebPartTitle;</Title>' +
    '<Description>$Resources:core,ContentEditorWebPartDescription;</Description>' +
    '<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>' +
'</WebPart>';

addWebPart('/','Pages/default.aspx',webPartXml,'Left',1,function(webPart){
    console.log(webPart.get_title() + ' has been added'); 
},function(sender,args){
    console.log(args.get_message());
});
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top