How to add pages / web-part zones / web-parts programmatically in SharePoint online using PnP JS?

326 Views Asked by At

I have created pages then added web-part zones / web-parts programmatically using below function,

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

Now, I need to create a page then add web-part zones / web-parts programmatically in SharePoint online using PnP JS.

Can anyone help me with the same?

1

There are 1 best solutions below

0
On

You could refer to this question: https://github.com/pnp/pnpjs/issues/557

Using PnPJS, You need to grab webpart xml in a page and add it in page content.

import { sp } from "@pnp/sp";
const mynewpageContent =
`<%@ Page Inherits="Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=16.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %> <%@ Reference VirtualPath="~TemplatePageUrl" %> <%@ Reference VirtualPath="~masterurl/custom.master" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>
<!--[if gte mso 9]><SharePoint:CTFieldRefs runat=server Prefix="mso:" FieldList="FileLeafRef,Comments,PublishingStartDate,PublishingExpirationDate,PublishingContactEmail,PublishingContactName,PublishingContactPicture,PublishingPageLayout,PublishingVariationGroupID,PublishingVariationRelationshipLinkFieldID,PublishingRollupImage,Audience,PublishingIsFurlPage,PublishingPageImage,PublishingPageContent,SummaryLinks,SummaryLinks2,SeoBrowserTitle,SeoMetaDescription,SeoKeywords,RobotsNoIndex"><xml>
<mso:CustomDocumentProperties>
<mso:PublishingPageContent msdt:dt="string"></mso:PublishingPageContent>
<mso:ContentType msdt:dt="string">Welcome Page</mso:ContentType>
<mso:PublishingPageLayout msdt:dt="string">https://contoso.sharepoint.com/sites/site/_catalogs/masterpage/ArticleLeft.aspx, Article Left</mso:PublishingPageLayout>
</mso:CustomDocumentProperties>
</xml></SharePoint:CTFieldRefs><![endif]-->
<title>Home</title></head>`;

(async () => {
    
    const page = await sp.web.getFolderByServerRelativeUrl('/sites/site/pages').files.add('mynewpage.aspx', mynewpageContent, true)
    console.log('Done');

})()
    .catch(console.warn);