Joost
Joost

Reputation: 97

Add nonce to script tag

I want to add a nonce to a dynamically constructed script tag. The below does NOT add any nonce to the generated script tag. Anyone an idea how the nonce can be added?

var _wss = document.createElement('script');
_wss.nonce = 'random-string';
_wss.type = 'text/javascript';
_wss.charset = 'utf-8';
_wss.async = true;
_wss.src = "url";
var __wss = document.getElementsByTagName('script')[0];
__wss.parentNode.insertBefore(_wss, __wss);

The result is:

<script type="text/javascript" charset="utf-8" async src="url"></script>

Expected result:

<script nonce="random-string" type="text/javascript" charset="utf-8" async src="url"></script>

Thanks!

Upvotes: 4

Views: 14473

Answers (2)

Chris Lear
Chris Lear

Reputation: 6742

I ran your code on this stackoverflow page, and it worked.

I think the problem you're having is that you're expecting to see the nonce as an attribute of the script tag, but it's only available in javascript as a property.

The tag looks like this

<script type="text/javascript" charset="utf-8" async="" src="url"></script>

But if you run

console.log(document.getElementsByTagName('script')[0].nonce)

it will show "random-string"

The reason is security. See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce#accessing_nonces_and_nonce_hiding. Specifically

For security reasons, the nonce content attribute is hidden (an empty string will be returned).

The nonce property is the only way to access nonces:

Upvotes: 9

Jax-p
Jax-p

Reputation: 8531

You have to use strict-dynamic CSP source instead of nonce if you want to dynamically import/construct scripts.

The strict-dynamic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. At the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored.

Source MDN - CSP: script-src

You can also read more about it and see some examples at Content Security Policy (CSP) Quick Reference Guide.

Upvotes: 3

Related Questions