Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  47] [ 4]  / answers: 1 / hits: 5276  / 3 Years ago, fri, april 16, 2021, 12:00:00

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!


More From » nonce

 Answers
1

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:



[#1472] Friday, April 9, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
Fri, May 10, 19, 00:00, 5 Years ago
;