0

How to include javascript function as a user custom action on every page in a site collection?

how can we achieve this using JSOM?

0

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

0

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

Add custom user action

Add custom user action

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

  • Thanks for the links, but i am in need of UCA not for ribbon or menu – Pradeep Oct 31 '18 at 7:13
  • Any update @pradeep – Shridhar J Joshi Nov 5 '18 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.