Wednesday, December 14, 2016

How to inject javascript in SharePoint Online with powershell

Hi All,

As we know that SharePoint Online recommended not to update master pages.
If we want to add/update master page we have to use inject JavaScript to any Site or Site Collection via a User Custom Action's ScriptLink property.

we can add user custom actions in different ways.

I. Using PowerShell:

i. Upload the files, like JQuery, custom javascript and css files.
ii. Now open powershell and connect to SharePoint online as below.

$urlAdmin =
$user = ""
$urlSite =

$passwordSecureString = ConvertTo-SecureString -string $password -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $user, $passwordSecureString

Connect-SPOService -Url $urlAdmin -Credential $credential

$spoCredentials = New-Object -TypeName Microsoft.SharePoint.Client.SharePointOnlineCredentials -argumentlist $user, $passwordSecureString

iii. Now add custom actions as below

#Injecting JQuery file
$spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($urlSite)
$spoCtx.Credentials = $spoCredentials
$spoCtx.RequestTimeout = "500000"
$newAction = $spoCtx.Site.UserCustomActions.Add();
$newAction.Location = "ScriptLink";
$newAction.scriptSrc = "~SiteCollection/SiteAssets/scripts/jquery-2.1.3.min.js";
$newAction.Sequence = 1001;

#Injecting custom javascript file
$newAction = $spoCtx.Site.UserCustomActions.Add();
$newAction.Location = "ScriptLink";
$newAction.scriptSrc = "~SiteCollection/SiteAssets/scripts/CustomJS.js";
$newAction.Sequence = 1002;

Thats it now you can add other javascript/css files from CustomJS.js files.

Its so simple right!!!

Here the complete code.