Add ApplicationInsights to your O365 SharePoint sites

If you use ApplicationInsights in your SharePoint Apps you might also want to include it in all sites of the hosting web. You can do this by injecting the corresponding JavaScript using the client side object model (CSOM) and UserCustomActions.

Go to and open your ApplicationInsights-Application or create a new one. Go to “Quick start” – “Get code to monitor my web pages” and copy the code insight the script tags.


Save the script to a JavaScript file and upload it to your O365 site (i.e. to /Style%20Library).


Use the following PowerShell script to inject the JavaScript file without modifying the master page or deploying any kind of solution.

$username = "" 
$password = "<your password>" 
$url      = ""
$jsurl    = "$url/Style%20Library/AppInsights.js"

$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force 


$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url) 
$clientContext.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword) 

if (!$clientContext.ServerObjectIsNull.Value) 
    Write-Host "Connected to SharePoint Online site: '$Url'" -ForegroundColor Green 

$id       = "AppInsights"
$revision    = [guid]::NewGuid().ToString().Replace("-", "")
$jsLink      = "$($jsurl)?rev=$revision"
$scriptBlock = "var headID = document.getElementsByTagName('head')[0]; 
                var newScript = document.createElement('script');
                newScript.type = 'text/javascript';
                newScript.src = '$jsLink';

$web = $clientContext.Web

$existingActions = $web.UserCustomActions

foreach ($action in $existingActions)
    if ($action.Description -eq $id -and $action.Location -eq "ScriptLink")

$newAction = $existingActions.Add()
$newAction.Description = $id
$newAction.Location = "ScriptLink"
$newAction.ScriptBlock = $scriptBlock

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s