SharePoint Online: PowerShell to Inject JavaScript using Custom Action

Requirement: Inject JavaScript into SharePoint Online using PowerShell

SharePoint Online Inject JavaScript using PowerShell:
Lets 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
$CustomActionTitle = "Google Analytics"
    #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

    #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"

        Write-Host -f Green "Custom Action Added Successfully!"
         write-host -f Yellow "Custom Custom Already Exists!"
Catch {
        write-host -f Red "Error Adding Custom Action!" $_.Exception.Message
This inserts the JavaScript under <head> tag
sharepoint online inject javascript powershell

1 comment:

Please Login and comment to get your questions answered!

Powered by Blogger.