Displaying Notification using Banner in SharePoint

Introduction

Imagine if we are doing site maintenance and want to send notifications about the updates being done on-site to owners. There are a couple of ways.

  • Sending a group chat via communication channels in teams
  • Sending an email notification

How about if there is a banner on the site that will show a message? This is something that can be done in minutes by following the steps.

The below code only works for SharePoint on-prem and SharePoint online with Classic Look and Feel. Please refer to the blog by Akash Kumhar, which gives a complete idea of the JS methods used to display different kinds of messages on SharePoint pages. Kudos to Akash. The following code is tested against SharePoint 2016 on-prem, and it should work for SharePoint Online sites with Classic Look and Feel. I will post the banner in SharePoint online in the coming articles. You can also refer to SharePoint nuts and bolts in the references section. 

Pre-requisites

You need to have PowerShell Modules for SharePoint On-Premise Environment installed on your machine. This is detailed in wordpress blog in the references section. Credit goes to Bram De Jagar. 

Register Custom Action to Show Banner

The following steps are needed to register a custom action. Custom Action can be defined as a feature that gets loaded during the runtime.

Step 1. Get the JS from the repository. Following is the JavaScript code that can be downloaded from the attached section. In this case, I have named it ShowNotification_Working_Final.js. 

function ShowStatusBarMessage(title, message) {  
    var statusId = SP.UI.Status.addStatus(title, message, true);  
    SP.UI.Status.setStatusPriColor(statusId, 'yellow'); /* Set a status-color */  
    return statusId;  
}  
function retrieveListItems(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Notifications');
        
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
        '<View><Query><Where><Eq><FieldRef Name=\'ID\'/>' + 
        '<Value Type=\'Number\'>1</Value></Eq></Where></Query>' + 
        '<RowLimit>10</RowLimit></View>'
    );
    this.collListItem = oList.getItems(camlQuery);
        
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded), 
        Function.createDelegate(this, this.onQueryFailed)
    ); 
}

function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
        
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += oListItem.get_item('Description');
    }

   // alert(listItemInfo.toString());
   //return listItemInfo;
   console.log("The returned message: " + listItemInfo);
   var nid = ShowStatusBarMessage(title, listItemInfo, true);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + 
        '\n' + args.get_stackTrace());
}
var title = "";  
//var str1 = "";
setTimeout (function(){
    var srcSite = _spPageContextInfo.siteAbsoluteUrl;
    str1 = retrieveListItems(srcSite);
    //console.log("the returned message: " + str1);
},2000)  

Step 2. Upload the JS to the CustomScripts folder inside Style Library. The script can be uploaded anywhere. The reason to keep inside ‘Style Library’ is to have all the styling in one place since the banner is kind of a style in SharePoint pages. The reason to create a folder called ‘CustomScripts’ just to avoid any updates to this folder during the SharePoint cumulative updates.

 

Step 3. Upload the Banner template to the List Templates gallery. This is a simple OOTB list with the following data. You can also create a custom list with the Title 'Notifications' and create the below 'Description' column. 

  • List Title: Notifications
  • Title: Single line of text
  • Description: Multi-line text with basic html formatting

You can download the list template from the attachments. Please note that whatever message you put in Description, the same will be show in banner, thus by giving the site users flexibility in updating the banner messages. 

Step 4. Register the Custom Action called ‘ContosoITMigrationBanner’ using PowerShell script. Below is the PS script used to register the custom Action of type ‘ScriptLink’. ScriptLink feature is like the ‘Application Customizer’ feature in SharePoint online, which injects or loads the JS during the runtime without any changes to the system/application pages. More about the ‘ScriptLink’ feature can be found in the references section.

$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")  
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")  
#Must be SharePoint Site Collection Administrator URL  
$siteUrl = Read-Host -Prompt "Input Site URL"  
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)  
$site = $ctx.Site  
$username = Read-Host -Prompt "Input Admin ID"  
write-host "Please enter your password"  
$password = read-host -AsSecureString  
$ctx.Credentials = New-Object System.Net.NetworkCredential($username, $password)  
$ctx.Load($site)  
$ctx.ExecuteQuery()  
$userCustomActions = $site.get_userCustomActions();  
$newUserCustomAction = $userCustomActions.add();  
$newUserCustomAction.set_location('ScriptLink');  
$newUserCustomAction.set_scriptSrc('~SiteCollection/Style Library/CustomScripts/ShowNotification_Working_Final.js');  
$newUserCustomAction.set_sequence(10);  
$newUserCustomAction.set_title('ContosoITMigration Banner');  
$newUserCustomAction.set_description('ContosoITMigration Banner');  
$newUserCustomAction.update();  
$ctx.ExecuteQuery()  

Below is the screenshot of the banner that is getting displayed after registering the custom Action.

Also, the message can be changed by going to the Notifications list and updating the description. Whatever description is updated in the list will be shown in the banner, thus giving you the flexibility to update the notification. 

Unregister Custom Action to Remove Banner

At any point in time, if you think the banner is no longer needed, you can do that by unregistering the custom Action. You can run the below PowerShell script to unregister the custom Action, which will clean up the banner from the SharePoint site. Below is the link to Unregister Custom Action, which will eventually remove the banner. 

$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")  
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")  
#Must be SharePoint Site Collection Administrator URL  
$siteUrl = Read-Host -Prompt "Input Site URL"  
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)  
$site = $ctx.Site  
$username = Read-Host -Prompt "Input Admin ID"  
write-host "Please enter your password"  
$password = read-host -AsSecureString  
$ctx.Credentials = New-Object System.Net.NetworkCredential($username, $password)  
$ctx.Load($site)  
$ctx.ExecuteQuery()  
$userCustomActions = $site.get_userCustomActions();  
$ctx.Load($userCustomActions)  
$ctx.ExecuteQuery()  
foreach($action in $userCustomActions) { 
#Update the name of the custom action that needs to be removed 
    if ($action.title -eq 'GMFITAdminTest URL Redirection') {  
        $action.DeleteObject()  
        Write-Host "$($action.title) custom action deleted" -ForegroundColor Yellow
        $ctx.ExecuteQuery()  
    }  
}  

$ctx.ExecuteQuery()

References