SharePoint Online: PowerShell to Inject JavaScript using Custom Action
Requirement: Inject JavaScript into SharePoint Online using PowerShell.
SharePoint Online Inject JavaScript using PowerShell:
Let’s insert JavaScript to SharePoint Online using PowerShell without modifying the Master page!
#Load SharePoint CSOM Assemblies
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"
#Set parameter values
$SiteURL="https://Crescent.sharepoint.com"
$CustomActionTitle = "Google Analytics"
Try{
#Get Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
#Get Existing Custom Actions
$Site = $Ctx.Site
$UserCustomActions= $Site.UserCustomActions
$Ctx.Load($UserCustomActions)
$Ctx.ExecuteQuery()
#Check if the CustomAction Exists already
$CustomAction = $UserCustomActions | Where { $_.Title -eq $CustomActionTitle } # | Select -First 1
If($CustomAction -eq $Null)
{
#Add new custom action
$UserCustomAction = $Ctx.Site.UserCustomActions.Add()
#Set the Properties of the custom action
$UserCustomAction.Name = $CustomActionTitle
$UserCustomAction.Title = $CustomActionTitle
$UserCustomAction.Location = "ScriptLink"
$UserCustomAction.Sequence = 1
$UserCustomAction.ScriptSrc ="~SiteCollection/SiteAssets/ga.js"
$UserCustomAction.Description = "Google analytics Tracking Script"
$UserCustomAction.Update()
$Ctx.ExecuteQuery()
Write-Host -f Green "Custom Action Added Successfully!"
}
Else
{
write-host -f Yellow "Custom Custom Already Exists!"
}
}
Catch {
write-host -f Red "Error Adding Custom Action!" $_.Exception.Message
}
This inserts the JavaScript under the <head> tag.
This adds JavaScript to site-wide! If you want to add a piece of JavaScript to a modern page, use the modern script editor web part: How to add JavaScript to SharePoint online modern page?
Very informative and really helpful!