How to inject javascript to SharePoint or Office 365 master pages using CSOM

In office 365 environment, Microsoft had suggested not to modify the master pages. So to avoid modification, we can inject JavaScript at run time to the Master Pages of Office 365. This can be accomplished using the below CSOM Code (concocted by our Offshore SharePoint Developers) in any provider hosted model app development. Fundamentally we are creating Custom Action at run time and injecting JavaScript using custom actions.

These below mentioned code blocks will help you to inject the JavaScript to SharePoint master pages by using CSOM (Client Object Model). In this below mentioned examples I am going to add SP notification messages to SharePoint site. Similarly, you can inject your custom JavaScript functions to SharePoint or Office 365 sites.

[code lang=”c”]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Microsoft.SharePoint.Client;

namespace customaction
{
class Program
{
static void Main(string[] args)
{
StringBuilder statusBarMsgBuilder = new StringBuilder(@”ExecuteOrDelayUntilScriptLoaded(function(){
var statusID = SP.UI.Status.addStatus(‘Title:’, ‘Type your status bar message here you want to add.’, true);
SP.UI.Status.setStatusPriColor(statusID, ‘yellow’);},’sp.js’)”);

using (ClientContext context = new ClientContext(“http://yoursiteurl”))
{
context.Credentials = new NetworkCredential(“UserName”, “Password”);
Web myWeb = context.Web;
context.Load(myWeb, mW => mW.UserCustomActions);
context.ExecuteQuery();

UserCustomActionCollection myCustomActionColl = myWeb.UserCustomActions;

var myNewCustomAction = myCustomActionColl.Add();
myNewCustomAction.Description = “My New Custom Action”;
myNewCustomAction.Location = “ScriptLink”;
myNewCustomAction.ScriptBlock = statusBarMsgBuilder.ToString();
myNewCustomAction.Update();

myWeb.Update();
context.ExecuteQuery();
}
}
}
}

[/code]

Hope this information will help you!

This solution is brought to you by our SharePoint professionals…

Softree Technology employs SharePoint consultants, who are experienced in writing for a multiplicity of SharePoint verticals including technical, promotional, creative, branding content, cataloguing and ethical media comprising journalism.

With more than 10 years of industry experience these professionals have the best resources to deliver optimum results. They have been satisfying customers with some of the best SharePoint Strategies.  

Tags: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *