0

I'm trying on my site's homepage to close a web part programmatically using Javascript. The code fires, but the web part doesn't close. How can I close the web part programmatically?

var clientContext = new SP.ClientContext('/');
var oFile = clientContext.get_web().getFileByServerRelativeUrl('/default.aspx');
var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.user);
var webParts = limitedWebPartManager.get_webParts();
var webPartDefinition = webParts.getById(webPartGuid);
webPartDefinition.closeWebPart(); // webPartDefinition.deleteWebPart();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onRemoveSucceeded), Function.createDelegate(this, this.onRemoveFailed));

Known:

  • The same code works for deleting the web part (substitute deleteWebPart() for closeWebPart())
  • webPartGuid is known before the code fires (again: delete succeeds w/o problem)
  • onRemoveSucceeded is getting called when I'm trying to close, but the web part is still open
0

Where webPartDiv is the jQuery object of the web part's <div> having the 'WebPartID' attribute:

function CloseWebPart(webPartDiv) {
    var webPartHtmlDomObject = GetHtmlDomObjectFromJqueryObject(webPartDiv);
    MSOLayout_RemoveWebPart(webPartHtmlDomObject);
}

function GetHtmlDomObjectFromJqueryObject(jQueryObject) {
    var result = jQueryObject.get(0);
    return result;
}

MSOLayout_RemoveWebPart lives in the SharePoint JS files.

0

After you've closed the webpart, call webPartDefinition.saveWebPartChanges(); before proceeding with the query exectution.

 webPartDefinition.closeWebPart();
 webPartDefinition.saveWebPartChanges(); // add this line
 clientContext.executeQueryAsync(Function.createDelegate(this, this.onRemoveSucceeded), Function.createDelegate(this, this.onRemoveFailed));

That worked for me.

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.