Follow by Email

Wednesday, October 25, 2017

Adding Custom Action to SharePoint Online site

In this post, I'm providing the SPO powershell script which you can run from SPO management shell to add a new custom action to specific site.


You can use this script to render scripts on specific pages inside a site and  there by add any new options to users/ hide any option from end users.


Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
# Authenticate with the SharePoint site.
#
$actionName = "EM_SPO_JOSPODELWEB_JS_Injection"
$actionType = "ScriptLink"
$actionSourceFile ="https://yourtenant.sharepoint.com/sites/JoSPO/SiteAssets/HideSiteDeletion.js"
$siteUrl = Read-Host -Prompt "Enter web url:"
$username = Read-Host -Prompt "Enter Username:"
$password = Read-Host -Prompt "Enter password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
# SharePoint Online
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials
$rootWeb = $ctx.Web
$ctx.Load($rootWeb)
$actions = $rootWeb.get_userCustomActions()
$ctx.Load($actions)
$ctx.ExecuteQuery()
if($actions)
{
$actionsToDelete = @()
foreach($action in $actions)
{
if($action.get_description() -eq $actionName -and $action.get_location() -eq $actionType) {
Write-Host "Action found:" $action.get_description() -foregroundcolor white -backgroundcolor Green
$actionsToDelete += $action
}
}
foreach($actionToDelete in $actionsToDelete) {
    $actionToDelete.deleteObject()
Write-Host "Action deleted" -foregroundcolor white -backgroundcolor Green
}
$ctx.ExecuteQuery()
}
Write-Host "Installing action"  -foregroundcolor white -backgroundcolor Green
$newAction = $actions.add();
$newAction.set_description($actionName);
$newAction.set_location('ScriptLink');
$scriptBlock = 'var headIDDetails = document.getElementsByTagName("head")[0];var newScriptDetails = document.createElement("script");newScriptDetails.type = "text/javascript";newScriptDetails.src="';
$scriptBlock += $actionSourceFile + '?ver=' + (Get-Date) ;
$scriptBlock += '";headIDDetails.appendChild(newScriptDetails);';
$newAction.set_scriptBlock($scriptBlock);
$newAction.update();
$ctx.ExecuteQuery();
Write-Host "Action" $newAction.Description "installed" -foregroundcolor white -backgroundcolor Green