How to include javascript function as a user custom action on every page in a site collection?
how can we achieve this using JSOM?
Why use JSOM? With powershell you can add more scripts at once by few lines:
# To Install SharePointPnPPowerShellOnline module uncomment the line below
#Install-Module SharePointPnPPowerShellOnline
$siteUrl = "https://xxxxxxxx.sharepoint.com"
# Connect to a SPO Site
$cred = Get-Credential
Connect-PnPOnline $siteUrl -Credentials $cred
# Injects a reference to the js libraries to all pages within the current site collection
Add-PnPJavaScriptLink -Name jQuery -Url "/Style Library/exe/scripts/jquery/jquery-3.3.1.min.js" -Sequence 9990 -Scope Site
Add-PnPJavaScriptLink -Name BootStrap -Url "/Style Library/exe/BootStrap/js/bootstrap.min.js" -Sequence 9991 -Scope Site
Add-PnPJavaScriptLink -Name ZSSK -Url "/Style Library/exe/scripts/ZSSK/ZSSK_MasterPage.js" -Sequence 9994 -Scope Site
Add-PnPJavaScriptLink -Name Moment -Url "/Style Library/exe/scripts/Moment/moment-with-locales.min.js" -Sequence 9995 -Scope Site
You can try out the user custom action at site collection level, where you can provide the link for js file.
Please let me know, if you may need any further information Refer
Update To add the js file on site you can try below code snippet
Site site = clientContext.Site;
UserCustomAction customAction = site.UserCustomActions.Add();
customAction.Location = "ScriptLink";
customAction.ScriptSrc = String.Format("{0}://{1}/Scripts/HelloWorld.js", Request.Url.Scheme, Request.Url.Authority);
customAction.Sequence = 1000;
customAction.Update();
clientContext.ExecuteQuery();
Ref Script Src
The easiest way to add Script and Brand your SharePoint and SharePoint Online
You can use the below code to add JS function on a site collection:
var clientContext = SP.ClientContext.get_current();
var userCustomActions = clientContext.get_site().get_userCustomActions();
clientContext.load(userCustomActions);
var action = userCustomActions.add();
action.set_location("ScriptLink");
action.set_title("TestFunction");
action.set_description("Test Script block desc");
// your javascript function
// you can replace this with a textArea field and as user input
var block = [
"(function(){",
"alert('hello');",
"})();"
].join("");
action.set_scriptBlock(block);
action.set_sequence(1000);
action.update();
clientContext.load(action);
clientContext.executeQueryAsync(function(){
console.log("success");
},function(){
console.log("error");
});
Modified from - UserCustomActionsConfigPage
Reference - sp-usercustomactions.js