Inject custom JavaScript file to all pages
I want add script into site
without editing master page. Using JavaScript Injection we can easily add our
custom script into all pages.
Below PowerShell script to
inject custom file to all pages.
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$SiteURL = "http://dotnetsharepoint.com/sites/PublishingSite/"
$actionName = "Lakshmi_JS_INjection"
$actiontype = "ScriptLink"
#Custom Script File
$actionSourceFile ="http://dotnetsharepoint.com/sites/PublishingSite/Documents/Test%20Inject.js"
$Context =New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$web = $Context.Web
$Context.Load($web)
$context.Load($web.Webs)
$Context.ExecuteQuery()
if($web)
$Context.ExecuteQuery()
if($web)
{
try
{
#for all subsites
foreach($web in $web.Webs)
foreach($web in $web.Webs)
{
$actions = $web.get_userCustomActions();
$Context.Load($actions)
$Context.ExecuteQuery()
if($actions)
{
{
#Delete existing script inject
foreach($action in $actions)
{
if($action.get_description() -eq $actionName -and $action.get_location() -eq $actionType){
$action.deleteObject()
}
}
}
$newAction = $actions.add();
}
}
}
$newAction = $actions.add();
$newAction.set_description($actionName);
$newAction.set_location('ScriptLink');
$scriptBlock = 'var headID = document.getElementsByTagName("head")[0];var newScript = document.createElement("script");newScript.type ="text/javascript";newScript.src ="';
$scriptBlock += $actionSourceFile + '?ver=' +(Get-Date);
$scriptBlock += '";headID.appendChild(newScript);';
$newAction.set_scriptBlock($scriptBlock);
$newAction.update();
$Context.ExecuteQuery();
Write-Host "Added"
}
}
catch
{
Write-Host "error"
}
}