How to Inject/Apply Javascript in all pages using CSOM in Office 365

In office 365, you are not advised to change/customize the master pages. In that case, only way to apply JavaScript is to inject the code at run time. To inject JavaScript code at run time, we use Custom Action in CSOM. Below are the sample code to inject Custom.js java script into all the pages.

//Upload the Javascript File

file = styleLibrary.RootFolder.Files.Add(new FileCreationInformation {
Content = Encoding.UTF8.GetBytes(fileContents),
Overwrite = true,
Url = “Custom.js”

//Check in the Javascript file

file.CheckIn(String.Empty, CheckinType.MajorCheckIn);

 // Register Custom Action
UserCustomAction customAction = site.UserCustomActions.Add();
customAction.Location = “ScriptLink”;
customAction.ScriptSrc = “~SiteCollection/Style Library/Custom.js”;
customAction.Sequence = 1000;

Hope it helps you guys!!! Happy SharePointing !!!

Leave a Reply

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