Step by Step Procedure to Add a JS file to all pages in a SPFx Modern Pages using SharePoint Framework Extension


Sathish Nadarajan
SharePoint MVP
Published On :   12 May 2018
Visit Count
Today :  5    Total :   2065



There are a lot of purpose for the SharePoint Framework Extension. One among them is to add a JS file on the Modern Pages. Since the modern team site and the communication does not allow us to edit the master pages (at least by the time, I write this article), it is very tough to add a custom JS to the Pages.

In the below example, let us see how to create an extension and add a JS file to the page.

1. Go to the folder and create the Extension using the Yo commands.

2. The below screen shots does not require much explanation. Hence, keeping only the screen shots here.

clip_image002

clip_image004

clip_image006

clip_image008

clip_image010

clip_image012

clip_image014

3. Once the extension created, the solution will be as below.

clip_image016

4. Open the Package-solution.json file and add a feature. The complete code will be as below.

 {
   "$schema": "https://dev.office.com/json-schemas/spfx-build/package-solution.schema.json",
   "solution": {
     "name": "extension-demo-client-side-solution",
     "id": "63fc1117-3fc1-45b4-abf6-453240fd78d1",
     "version": "1.0.0.0",
     "includeClientSideAssets": true,
     "features": [
       {
         "title": "MyExtension - Add JS Files.",
         "description": "Deploys a custom action with ClientSideComponentId association",
         "id": "c9fab333-d9e3-402b-aa7f-99d83a898a15",
         "version": "1.0.0.0",
         "assets": {
           "elementManifests": [
             "elements.xml"
           ]
         }
       }
     ]
   },
   "paths": {
     "zippedPackage": "solution/extension-demo.sppkg"
   }
 }
 

5. On the Write-Manifest.json, give the URL of the SharePoint CDN.

 {
   "$schema": "https://dev.office.com/json-schemas/spfx-build/write-manifests.schema.json",
   "cdnBasePath": "/sites/CommunicationSiteTopic/SiteAssets/ExtensionFiles"
 }
 

6. In the SharePoint folder, create a subfolder called assets and create an element.xml

7. The file content will be,

 <?xml version="1.0" encoding="utf-8"?>
 <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
     <CustomAction
         Title="AddJsFilesApplicationCustomizer"
         Location="ClientSideExtension.ApplicationCustomizer"
         ClientSideComponentId="1707ef82-309e-40b7-9748-7a8e3d04a2c9">
     </CustomAction>
 </Elements>
 

8. The ClientsideComponentID is the one which we need to copy from the Extension Manifest.json.

 {
   "$schema": "https://dev.office.com/json-schemas/spfx/client-side-extension-manifest.schema.json",
 
   "id": "1707ef82-309e-40b7-9748-7a8e3d04a2c9",
   "alias": "MyExtensionApplicationCustomizer",
   "componentType": "Extension",
   "extensionType": "ApplicationCustomizer",
 
   // The "*" signifies that the version should be taken from the package.json
   "version": "*",
   "manifestVersion": 2,
 
   // If true, the component can only be installed on sites where Custom Script is allowed.
   // Components that allow authors to embed arbitrary script code should set this to true.
   // https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
   "requiresCustomScript": false
 }
 
 

9. Edit the MyExtensionApplicationCustomizer.ts file as below.

 import { override } from '@microsoft/decorators';
 import { Log } from '@microsoft/sp-core-library';
 import {
   BaseApplicationCustomizer
 } from '@microsoft/sp-application-base';
 import { Dialog } from '@microsoft/sp-dialog';
 
 import * as strings from 'MyExtensionApplicationCustomizerStrings';
 
 const LOG_SOURCE: string = 'MyExtensionApplicationCustomizer';
 
 /**
  * If your command set uses the ClientSideComponentProperties JSON input,
  * it will be deserialized into the BaseExtension.properties object.
  * You can define an interface to describe it.
  */
 export interface IMyExtensionApplicationCustomizerProperties {
   // This is an example; replace with your own property
   testMessage: string;
 }
 
 /** A Custom Action which can be run during execution of a Client Side Application */
 export default class MyExtensionApplicationCustomizer
   extends BaseApplicationCustomizer<IMyExtensionApplicationCustomizerProperties> {
 
     private _JS: string = "https://*******.sharepoint.com/sites/CommunicationSiteTopic/Shared%20Documents/MyScript.js";
   @override
   public onInit(): Promise<void> {
     
     let articleRedirectScriptTag: HTMLScriptElement = document.createElement("script");
       articleRedirectScriptTag.src = this._JS;
       articleRedirectScriptTag.type = "text/javascript";
       document.body.appendChild(articleRedirectScriptTag);
 
       return Promise.resolve();
   }
 }
 

10. The file will look like below.

clip_image018

clip_image020

11. With these changes, let us build the solution and bundle, package, deploy the solution.

12. The commands used are,

a. Gulp build

b. Gulp bundle –ship

c. Gulp package-solution –ship

13. Now, copy the contents inside the temp\deploy folder to the CDN path.

14. Upload the SPPKG file to the Appcatalog site.

15. Come back to the site, which we want to deploy the APP and add the app.

16. clip_image022

17. It will take few seconds to get added.

18. Once, it got deployed, the MyScript.JS has been added on all the pages.

19. I have written only the alert on the JS file. Hence, when I refresh any page, I will get the alert loaded on the page.

clip_image024

20. The same TS file can be altered to load the JS files only on few pages like below.

 if((document.location.href).toLowerCase().indexOf("home.aspx") >= 0)
     {
 //Add the piece of code to add the HTMLScriptElement to the DOM Element
 }
 

A very straight forward method to add a Custom JS on the page in Modern pages.

DOWNLOAD SOURCE HERE

Happy Coding,

Sathish Nadarajan.

Categories