In Razor, you can check if a Content Security Policy (CSP) nonce attribute already exists on a script tag using a combination of C# and JavaScript. You’ll need to inspect the rendered HTML and check for the presence of the nonce attribute.

Here’s how you can do it:

  1. In your Razor .cshtml page, set a C# variable to indicate whether the nonce attribute is already present on the script tag.
@{
    // Your script source URL
    string scriptSrc = "your-script-source.js";

    // Check if the nonce attribute is already present on the script tag
    bool hasNonce = false;
    foreach (var item in PageContext.HttpContext.Items["CspScriptNonces"] as IList<string>)
    {
        if (item.Contains(scriptSrc))
        {
            hasNonce = true;
            break;
        }
    }
}

Now, in your JavaScript section, you can access the hasNonce variable to determine if the nonce attribute exists on the script tag.

<script>
    if (@hasNonce)
    {
        console.log("The nonce attribute already exists on the script tag.");
        // Do something if the nonce attribute exists
    }
    else
    {
        console.log("The nonce attribute does not exist on the script tag.");
        // You can choose to add the nonce attribute here if desired
    }
</script>

In the code above, the C# variable hasNonce is set based on whether the nonce attribute is found in the CspScriptNonces collection. The CspScriptNonces collection contains the URLs of scripts along with their corresponding nonce values that have already been rendered on the page.

In the JavaScript section, we access the hasNonce variable to perform actions based on whether the nonce attribute exists or not. You can choose to add the nonce attribute if it does not exist.

Please note that this approach assumes that you have already implemented the @Html.CspScriptNonce() method correctly in your Razor .cshtml page to add the nonce attribute to your script tags. If you haven’t added nonces to your script tags using @Html.CspScriptNonce(), this check won’t work.