1

I have tried to create webpart page using ECMA script, but did not get the right solution. How we can create web part page using ECMA script? Below is my code:

<input id="createPageBtn" type="button" value="Create Page">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script language="javascript">

var siteUrl = '/sites/MySiteCollection';
var serverRelativeUrl = '/Pages/aaa.aspx';

addWebPart();

function addWebPart() {

    alert('test1');

 var clientContext = SP.ClientContext.get_current();
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);

    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);

    var webPartXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' + 
        '<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' + 
        ' xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"' + 
        ' xmlns=\"http://schemas.microsoft.com/WebPart/v2\">' + 
        '<Title>My Web Part</Title><FrameType>Default</FrameType>' + 
        '<Description>Use for formatted text, tables, and images.</Description>' + 
        '<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>' + 
        '<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>' + 
        '<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>' + 
        '<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>' + 
        '<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />' + 
        '<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />' + 
        '<MissingAssembly>Cannot import this Web Part.</MissingAssembly>' + 
        '<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />' + 
        '<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, ' + 
        'PublicKeyToken=94de0004b6e3fcc5</Assembly>' + 
        '<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' + 
        '<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />' + 
        '<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">' + 
        '<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>' + 
        '<PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>';

    var oWebPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
    this.oWebPart = oWebPartDefinition.get_webPart();

    limitedWebPartManager.addWebPart(oWebPart, 'wpz', 1);

    clientContext.load(oWebPart);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
alert('done');
    alert('Web Part added: ' + oWebPart.get_title());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}



</script>
  • code executing well ,and showing me alert('Done') but web part not visible on Publishing page. i tryied "Left",Right,middle,main webpart zone but issue remain same(not visible). when i try to add on web part page its working. so please any one help me ,how to add webpart on Publishing page. – Sohan Singh May 8 '15 at 18:29
1

I guess you are trying to insert web part into Rich Text Editor (RTE) of publishing page (e.g., for Body only page layout), in that case the solution would consist of two steps:

  1. insert web part into hidden zone template named wpz since the publishing page does not contain any public zone templates
  2. insert special marker for web part into PublishingPageContent field (see insertWebPartMarker function for a details). This is a mandatory step, marker is intended for selecting web part once the page is opened in edit mode, otherwise web part will not be visible on page

Complete example

How to insert web part into publishing page:

function addWebPart(webUrl, pageUrl,webPartXml,zoneId,zoneIndex){
    var ctx = new SP.ClientContext(webUrl);
    var file = ctx.get_web().getFileByServerRelativeUrl(pageUrl);
    var wpm = file.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    var importedWebPart = wpm.importWebPart(webPartXml);
    var webPart = wpm.addWebPart(importedWebPart.get_webPart(), zoneId, zoneIndex);
    ctx.load(webPart);

    var deferred = $.Deferred();
    ctx.executeQueryAsync(function() {
        deferred.resolve(file,webPart);
    },
    function(sender,args){
        deferred.reject(sender, args);
    });
    return deferred.promise();
}


function insertWebPartMarker(file,webPartDef)
{
    var ctx = webPartDef.get_context();
    var marker = String.format("<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>", webPartDef.get_id());
    var item = file.get_listItemAllFields();
    item.set_item("PublishingPageContent",marker); 
    item.update();
    var deferred = $.Deferred();
    ctx.executeQueryAsync(function() {
        deferred.resolve();
    },
    function(sender,args){
        deferred.reject(sender, args);
    });
    return deferred.promise();
}


function addWebPartIntoRTE(webUrl, pageUrl,webPartXml) 
{
    var zoneId = 'wpz';
    var zoneIndex = 0;
    return addWebPart(webUrl,pageUrl,webPartXml,zoneId,zoneIndex).then(insertWebPartMarker);
}

Usage

var contentEditorSchemaXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' + 
        '<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' + 
        ' xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"' + 
        ' xmlns=\"http://schemas.microsoft.com/WebPart/v2\">' + 
        '<Title>My Web Part</Title><FrameType>Default</FrameType>' + 
        '<Description>Use for formatted text, tables, and images.</Description>' + 
        '<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>' + 
        '<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>' + 
        '<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>' + 
        '<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>' + 
        '<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />' + 
        '<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />' + 
        '<MissingAssembly>Cannot import this Web Part.</MissingAssembly>' + 
        '<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />' + 
        '<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, ' + 
        'PublicKeyToken=94de0004b6e3fcc5</Assembly>' + 
        '<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' + 
        '<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />' + 
        '<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">' + 
        '<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>' + 
        '<PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>';



addWebPartIntoRTE(_spPageContextInfo.webAbsoluteUrl,'/sites/news/Pages/News-123.aspx',contentEditorSchemaXml).then(logSuccess,logError);

function logError(sender,args){
   console.log('An error occured: ' + args.get_message());
}

function logSuccess(sender,args){
   console.log('Web Part has been added successfully.');
}

Update

How to insert web part on the page on button click:

$('#createPageBtn').click(function(){
    addWebPartIntoRTE(_spPageContextInfo.webAbsoluteUrl,'/sites/news/Pages/News-123.aspx',contentEditorSchemaXml).then(logSuccess,logError);
});
  • Hi Vadim, How can i pass file and webpartDef parameter in insertWebPartMarker(file,webPartDef) – Sohan Singh May 10 '15 at 1:59
  • 1) file corresponds to File object, see: var file = ctx.get_web().getFileByServerRelativeUrl(pageUrl); 2)webPartDef corresponds to WebPartDefinition object var webPart = wpm.addWebPart(importedWebPart.get_webPart(), zoneId, zoneIndex); They are passed from addWebPart into insertWebPartMarker function – Vadim Gremyachev May 10 '15 at 8:39
  • Since I've posted a complete example, you could insert a web part on button click (see an Update section) – Vadim Gremyachev May 10 '15 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.