How to: Work with Web Parts on a Page Using JavaScript

Applies to: SharePoint Foundation 2010

Use classes in the SP.WebParts namespace to work with Web Parts through the client object model. The LimitedWebPartManager object enables you to access the collection of Web Parts on a SharePoint page within a shared or personal scope through the get_webParts function.

Updating the Title of a Web Part Using ECMAScript (JavaScript, JScript)

The following example changes the title of the second Web Part in the collection of Web Parts on the Default.aspx page of the specified website. The example uses a LINQ query expression to return only the title of each Web Part, and it calls the saveWebPartChanges() function to save changes. The executeQueryAsync(succeededCallback, failedCallback) function is called twice: first to return the collection of Web Parts so that the code can verify that Web Parts exist on the page, and second to effect changes in the database.

var siteUrl = '/sites/MySiteCollection';
var serverRelativeUrl = '/sites/MySiteCollection/Default.aspx';

function updateWebPartTitle() {

    this.clientContext = new SP.ClientContext(siteUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);

    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    this.collWebPart = limitedWebPartManager.get_webParts();

    clientContext.load(collWebPart);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.changeTitle), Function.createDelegate(this, this.onQueryFailed));
}

function changeTitle() {

    if (!collWebPart.get_count()) {
        alert('No Web Parts on this page.');
    }

    var oWebPartDefinition = collWebPart.get_item(2);
    this.oWebPart = oWebPartDefinition.get_webPart();
    oWebPart.set_title('My New Web Part Title');

    oWebPartDefinition.saveWebPartChanges();

    clientContext.load(oWebPart, 'TitleUrl');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    alert('Title changed for Web Part: ' + this.oWebPart.get_titleUrl());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Adding a Web Part to a Page Using JavaScript

The following example adds a custom content editor Web Part as the second Web Part, in order, within the left zone of the Default.aspx page for a specified website. The example defines the XML for the Web Part, passes this string to the importWebPart(webPartXml) function, and then calls the addWebPart(webPart, zoneId, zoneIndex) function to add the Web Part to the page.

var siteUrl = '/sites/MySiteCollection';
var serverRelativeUrl = '/sites/MySiteCollection/Default.aspx';

function addWebPart() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);

    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);

    var webPartXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' + 
        '<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' + 
        ' xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"' + 
        ' xmlns=\"https://schemas.microsoft.com/WebPart/v2\">' + 
        '<Title>My Web Part</Title><FrameType>Default</FrameType>' + 
        '<Description>Use for formatted text, tables, and images.</Description>' + 
        '<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>' + 
        '<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>' + 
        '<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>' + 
        '<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>' + 
        '<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />' + 
        '<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />' + 
        '<MissingAssembly>Cannot import this Web Part.</MissingAssembly>' + 
        '<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />' + 
        '<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, ' + 
        'PublicKeyToken=94de0004b6e3fcc5</Assembly>' + 
        '<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' + 
        '<ContentLink xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" />' + 
        '<Content xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\">' + 
        '<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>' + 
        '<PartStorage xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>';

    var oWebPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
    this.oWebPart = oWebPartDefinition.get_webPart();

    limitedWebPartManager.addWebPart(oWebPart, 'Left', 1);

    clientContext.load(oWebPart);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    alert('Web Part added: ' + oWebPart.get_title());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Deleting a Web Part from a Page Using JavaScript

The following example shows how to use the deleteWebPart() function to delete the first Web Part from the Home.aspx page of a specified website.

var siteUrl = '/sites/MySiteCollection';
var serverRelativeUrl = '/sites/MySiteCollection/SitePages/Home.aspx';

function retrieveWebParts() {

    this.clientContext = new SP.ClientContext(siteUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(server2RelativeUrl);

    this.limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    this.collWebPart = limitedWebPartManager.get_webParts();

    clientContext.load(collWebPart);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.deleteWebPart), Function.createDelegate(this, this.onQueryFailed));
}

function deleteWebPart () {

    if (!collWebPart.get_count()) {
        alert('No Web Parts to delete.');
    }

    var webPartDefinition = limitedWebPartManager.get_webParts().get_item(0);

    webPartDefinition.deleteWebPart();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
    
function onQuerySucceeded() {

    alert('Web Part deleted.');
}
function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

See Also

Concepts

Data Retrieval Overview

SharePoint Client Object Creation

SharePoint 2010 Client Object Model Guidelines

Common Programming Tasks in the JavaScript Object Model

Web Parts in SharePoint Foundation

Other Resources

JavaScript Class Library