如何使用JavaScript对象模型以编程方式将SharePoint客户端Web部件(应用程序部件)添加到页面?

时间:2015-01-12 06:22:36

标签: javascript sharepoint sharepoint-2013

有时需要以编程方式将AppPart(客户端webpart)添加到SharePoint页面(特别是在我们处理SharePoint托管应用程序时)。那么如何使用JSOM实现这个要求呢?

1 个答案:

答案 0 :(得分:0)

以下是达到上述要求的JavaScript代码:

开始前需要了解的事项 -

  • WepPart区域ID
  • WebPart区域索引

现在您需要客户端webpart(apppart)的XML以编程方式添加它。

  • 要获取此webpart XML,请手动将客户端webpart添加到任何页面。
  • 编辑webpart并允许导出数据。
  • 导出webpart(系统将提示您保存* .wepbart文件)

复制导出的webpart XML中的数据并准备一个字符串变量,如下所示:

var webPartXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' +
        '<webParts>' +
  '<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">' +
    '<metaData>' +
      '<type name="Microsoft.SharePoint.WebPartPages.ClientWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />' +
      '<importErrorMessage>Cannot import this Web Part.</importErrorMessage>' +
    '</metaData>' +
    '<data>' +
      '<properties>' +

        '<property name="TitleIconImageUrl" type="string" />' +
        '<property name="Direction" type="direction">NotSet</property>' +
        ...
        ...
        ...
        '<property name="ChromeState" type="chromestate">Normal</property>' +
      '</properties>' +
    '</data>' +
  '</webPart>' +
'</webParts>';

现在使用以下代码以编程方式使用JavaScript对象模型添加客户端webpart:

function addClientWebPart(pageName,webPartZoneID,webPartZoneIndex) {
var site = context.get_site();
var rootWeb = site.get_rootWeb();
context.load(rootWeb, 'ServerRelativeUrl');
context.load(site);
context.executeQueryAsync(function () {

    var rootUrl = rootWeb.get_serverRelativeUrl();

    pageFile = rootWeb.getFileByServerRelativeUrl(rootUrl + "/Pages/" + pageName + '.aspx');
    ////////////
    var limitedWebPartManager = pageFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);

    var webPartXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' +
        '<webParts>' +
  '<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">' +
    '<metaData>' +
      '<type name="Microsoft.SharePoint.WebPartPages.ClientWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />' +
      '<importErrorMessage>Cannot import this Web Part.</importErrorMessage>' +
    '</metaData>' +
    '<data>' +
      '<properties>' +

        '<property name="TitleIconImageUrl" type="string" />' +
        '<property name="Direction" type="direction">NotSet</property>' +
        ...
        ...
        ...
        '<property name="ChromeState" type="chromestate">Normal</property>' +
      '</properties>' +
    '</data>' +
  '</webPart>' +
'</webParts>';

    var webPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
    var webPart = webPartDefinition.get_webPart();

    limitedWebPartManager.addWebPart(webPart, webPartZoneID, webPartZoneIndex);

    context.load(webPart);

    context.executeQueryAsync(onAddAppPartQuerySucceeded, onAddAppPartQueryFailed);
 });
}