有时需要以编程方式将AppPart(客户端webpart)添加到SharePoint页面(特别是在我们处理SharePoint托管应用程序时)。那么如何使用JSOM实现这个要求呢?
答案 0 :(得分:0)
以下是达到上述要求的JavaScript代码:
开始前需要了解的事项 -
现在您需要客户端webpart(apppart)的XML以编程方式添加它。
复制导出的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);
});
}