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());
});