1

I get an error, when I try to get all web parts of a page.

var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();

//get all webparts for current site
var page = web.getFileByServerRelativeUrl(_spPageContextInfo.serverRequestPath);
var limitedWebPartManager = page.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webParts = limitedWebPartManager.get_webParts();

ctx.load(webParts, 'Include(WebPart.Properties, Id)');

ctx.executeQueryAsync(Function.createDelegate(this, function () {
    for (var i = 0; i < webParts.get_count(); i++) {
        // Do something
    }
}), function (e, a) {
    utility.log(a);
});

The error happens when calling webParts.get_count()

The error-message is:

the collection has not been initialized

The same error occurs when I use the enumerator of the collection.

But when I look into the object with the inspector, I can find the retrieved data of all webparts.

Some more information: The page is in a publishing page and the error occurs when I open the edit mode.

Has someone an idea how to solve it?

To iterate through the internal array does not look very nice ;)

  • Can you try this: ctx.load(webParts,'Include(WebPart)'); – Nadeem Yousuf-AIS Sep 7 '16 at 10:28
  • I can't reproduce it - does this happen always for you? Is there a way for me to reproduce it? – Mx. Sep 7 '16 at 13:53
  • It happens when I have a published page and I open the edit-mode. But not only random :/ – Philip Szalla Sep 7 '16 at 13:57
  • 1
    Sorry, I mean it happens randomly – Philip Szalla Sep 7 '16 at 14:15
  • @NadeemYousuf Sorry, but it does not work :( – Philip Szalla Sep 9 '16 at 13:12
1

I solved it with a workarround. It seems that SharePoint is not able to parse the response from the server sometimes.

var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();

//get all webparts for current site
var page = web.getFileByServerRelativeUrl(_spPageContextInfo.serverRequestPath);
var limitedWebPartManager = page.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webParts = limitedWebPartManager.get_webParts();

ctx.load(webParts, 'Include(WebPart.Properties, Id)');

ctx.executeQueryAsync(Function.createDelegate(this, function () {
    // Workarround when not correctly parsed
    webParts = webParts.$12_1 ? webParts : webParts.$5_0.$1t_0;

    for (var i = 0; i < webParts.get_count(); i++) {
        // Do something
    }
}), function (e, a) {
    utility.log(a);
});

In the object webParts.$5_0.$1t_0 is the correct SP.WebPartDefinitionCollection object.

| improve this answer | |

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.