Expand Minimize
This documentation is part of the BETA release and subject to change.

Use AddJsBlock to set and add a JS block.

PnP has an implementations to add JS blocks.

CheckId SPC029014
TypeName UseAddJsBlock
Severity Warning
Type Assembly

Standard SharePoint CSOM

var jsAction = new CustomActionEntity()
{
    Name = key,
    Location = "ScriptBlock",
    ScriptBlock = scriptBlock,
    Sequence = sequence
};

UserCustomAction targetAction;
    UserCustomActionCollection existingActions;

var site = (Site)clientObject;

existingActions = site.UserCustomActions;
site.Context.Load(existingActions);
site.Context.ExecuteQueryRetry();

targetAction = site.UserCustomActions.FirstOrDefault(uca => uca.Name == customAction.Name);

targetAction = existingActions.Add();

targetAction.Name = customAction.Name;
targetAction.Description = customAction.Description;
targetAction.Location = customAction.Location;
targetAction.Sequence = customAction.Sequence;

targetAction.ScriptBlock = customAction.ScriptBlock;
targetAction.ScriptSrc = customAction.ScriptSrc;

targetAction.Update();
if (clientObject is Web)
{
    var web = (Web)clientObject;
    web.Context.Load(web, w => w.UserCustomActions);
    web.Context.ExecuteQueryRetry();
}
else
{
    var site = (Site)clientObject;
    site.Context.Load(site, s => s.UserCustomActions);
    site.Context.ExecuteQueryRetry();
}

Using PnP
bool success = site.AddJsBlock(key, scriptBlock, 0);

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("Rencore.Analyzers.Assemblies.Rules.PnP.PnPBestPracticesGroup", "SPC029014:UseAddJsBlock", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.