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 = https://YOUR.TENANT-admin.sharepoint.com
$user = "administrator@YOUR.TENANT.onmicrosoft.com"
$password = "YOUR.TENANT.PASSWORD"
$urlSite = https://YOUR.TENANT.sharepoint.com/sites/TestSiteCollection

$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;
$newAction.Update();
$spoCtx.ExecuteQuery();

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

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

Its so simple right!!!

Here the complete code.