Thursday, March 10, 2016

SharePoint Online - JavaScript Injection with PowerShell

Scenario:
Updating the Master Page for SharePoint Online is not recommended by Microsoft now.....fine. So how do we change the UI then? And the answer is...by injecting JavaScript and CSS.

Solution:
You might want to watch this video of JavaScript injection which we will not follow here as injecting JavaScript and/or CSS through Visual Studio takes little bit of time as shown in the above video so I am putting pieces together to inject JavaScript using PowerShell very very...very quickly. Thank you Office Dev PnP's Erwin van Hunen.

Note: We are not going to use SharePoint Online Management Shell ;o) instead we will use Windows PowerShell.
  1. Install PnP PowerShell Cmdlets for SharePoint Online
    Url: https://github.com/officedev/pnp-powershell/releases
  2. Perform a quick test: Run the command below in Windows PowerShell to see if it is available
     Get-Command Add-SPOJavaScriptBlock
  3. Connect to the site where you want to push JavaScript code:
    Connect-SPOnline https://tenant.sharepoint.com/sites/portal
  4. Push the JavaScript code.
    Add-SPOJavaScriptBlock -Name MyScript -Script "alert('Hello World');"
    or
    Add-SPOJavaScriptLink -Name JQuery -Url https://code.jquery.com/jquery.min.js
  5. You are done. Now browse the site and you will get the annoying Hello World alert on all the pages.
Here is the complete script:
#
# This is a sample script and is provided as is.
# Author: Tahir Naveed
# Description: This script connects to a SPO site and 
# injects a JavaScript code block which will execute on all of the pages.
#
#

$url = "https://tenant.sharepoint.com/sites/portal"
$ScriptName = "MyScript"
$scriptBlock = "alert('Hello World');"

try
{
    #Connect to the SPO site
    Connect-SPOnline $url
    
    #Remove script if added before
    Remove-SPOJavaScriptLink -Name $ScriptName

    #Add the script
    Add-SPOJavaScriptBlock -Name $ScriptName -Script $scriptBlock

}
catch
{
    Write-Host "$_.Exception.Message"
}

Write-Host "Completed successfully." -ForegroundColor Green
Ref: Introduction to PnP PowerShell Cmdlets
Ref: OfficeDev/PnP-PowerShell Reference

Microsoft Flow - HTTP REST Call

In this blog post, I will cover what is a workflow and how we can create a workflow using Microsoft Flow that can make HTTP REST calls to br...