Skip to content

Instantly share code, notes, and snippets.

@vgrem vgrem/getWebParts.js
Created Jul 27, 2018

Embed
What would you like to do?
How to retrieve web parts along with web part type using SharePoint JSOM API
async function executeQuery(context) {
return new Promise((resolve, reject) => {
context.executeQueryAsync(function () {
resolve();
}, function (sender, args) {
reject(args);
});
});
}
function parseXml(xmlStr) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}
function parseWebPartSchema(schema){
let properties = {};
let schemaXml = parseXml(schema);
let node = schemaXml.querySelector('WebPart');
if(node) {//V2 format?
Array.from(node.childNodes).map( node => {
if(node.nodeName !== "#text")
properties[node.nodeName] = node.innerHTML;
})
}
else{
let node = schemaXml.querySelector('webPart');
properties["TypeName"] = node.querySelector('type').getAttribute('name');
Array.from(node.querySelector('properties').childNodes).map( node => {
if(node.nodeName !== "#text")
properties[node.getAttribute('name')] = node.innerHTML;
})
}
return properties;
}
async function getWebParts(file){
let ctx = file.get_context();
let webPartManager = file.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
let webPartDefs = webPartManager.get_webParts();
ctx.load(webPartDefs,"Include(Id,WebPart.Properties)");
await executeQuery(ctx);
return webPartDefs;
}
(async function() {
let fileUrl = "/HomePage.aspx"
let ctx = SP.ClientContext.get_current();
let file = ctx.get_web().getFileByServerRelativeUrl(fileUrl);
let webPartDefs = await getWebParts(file);
for (let webPartDef of webPartDefs.get_data()) {
let webPartId = webPartDef.get_id().toString();
let webPartManager = file.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
let webPartXml = webPartManager.exportWebPart(webPartId);
await executeQuery(ctx);
let props = parseWebPartSchema(webPartXml.get_value());
console.log(props.TypeName);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.