Adding custom javascript to sharepoint

Copper Contributor

Hi, i would like to create a webpart that pops up on a site at random location with something like "Congratz, you won!".

I am absolutely new to sharepoint development, but i am very familiar with java. 

So i guess i can manipulate the DOM somehow with javascript and insert somewhere my visible part of the webpart. I followed https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-... but i am already struggling. Where i can inject the javascript so it gets executed? Because everything is getting escaped (and the code is shown). 

I found some old code on one of our servers which "loads" some .js from inside a .ts like:

link = document.createElement("script");
        link.setAttribute('type', 'module');
        link.setAttribute('src', srcPath);
        link.setAttribute(dataIdentifier, 'true');
 
and then adding it with 
document.head.appendChild(link), but i am not sure if this is really how this is supposed to work or if there is something like "addJavascript(...)" or any other better approach to add javascript on client side.

Any help is very appreciated!

 

3 Replies

@oliwa66 If you want to inject custom JS/CSS on all SharePoint modern pages in site, you should use SPFx Application customizer instead.

 

OR if you want to ininject custom JS/CSS on only one modern pages in site, I will suggest you to use the Modern script editor web part: "Modern Script Editor" not available for SharePoint Online 

 

Check my answer for more information at: How can I include the same JS and CSS files on multiple SharePoint Modern Page? 

 

Note: DOM manipulation & CSS customizations based on HTML element id/classes are not recommended by Microsoft and some of your customization may break if Microsoft changes HTML element id/classes in new release updates.


Please click Mark as Best Response & Like if my post helped you to solve your issue. This will help others to find the correct solution easily. It also closes the item. If the post was useful in other ways, please consider giving it Like.

@ganeshsanap thanks, i'll take a look at modern script editor.

I already use the SPFx Application Framework, thats why i am asking if this is the way to go with loading the .js in that way as i mentioned.

@oliwa66 Yes, it is correct. If it is not working for you, try code given inside onInit() method in below links:

  1. InjectCssApplicationCustomizer.ts 
  2. HelloWorldApplicationCustomizer.ts 

Please click Mark as Best Response & Like if my post helped you to solve your issue. This will help others to find the correct solution easily. It also closes the item. If the post was useful in other ways, please consider giving it Like.