Frage

Would anybody be able to help me out on how to write a javascript snippet to add a webpart fra the gallary to a page using javascript?

I have tried several different solutions found here and elsewhere, but it does not seem to work (using SharePoint Online).

The usecase is the following; a workflow creates a new subsite and I want a simple "click at button"-script for the end user to easily setup the new page without having to actually mess with the normal "add webpart" process.

War es hilfreich?

Lösung

Oh well a bit more trying (and finding a simpler script) did the trick - also had to force loading of sp.js for it to work. For reference here's the working code in all its glory:

function addWebPart(serverRelativeUrl,WebpartZone) {

var webPartXml = '<?xml version="1.0" encoding="utf-8"?>' +
'<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">' +
    '<Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>' + 
    '<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' + 
    '<Title>$Resources:core,ContentEditorWebPartTitle;</Title>' +
    '<Description>$Resources:core,ContentEditorWebPartDescription;</Description>' +
    '<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>' +
'</WebPart>';

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

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

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

limitedWebPartManager.addWebPart(oWebPart, WebpartZone, 0);

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());}

<a href="#" onclick="addWebPart('/sites/udv/123456789/default.aspx','Left')">Click me</a>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit sharepoint.stackexchange
scroll top