CSP nonces with Cloudflare Workers


Like this blog, I use Cloudflare Workers to inject CSP (Content Security Policy) nonce in headers : https://scotthelme.co.uk/csp-nonces-the-easy-way-with-cloudflare-workers/

This is functional.
Next, I need to inject the nonce into all script tags. I use this script (in functions.php) :

add_filter( 'script_loader_tag', 'add_nonce_to_script', 10, 3 );
function add_nonce_to_script( $tag, $handle, $source ) {

$search = "type='text/javascript'";
$replace = "type='text/javascript' nonce='<?= html_escape($cspNonce); ?>'";
$subject = $tag;

$output = str_replace($search, $replace, $subject);
return $output;

The result is not the expected one, I get this kind of code :

script type="text/javascript" nonce="&lt;?= html_escape(); ?&gt;&lt;![CDATA[html5-dom-document-internal-cdata"

The problem probably comes from this line, but I don’t know how to correct it :

$replace = "type='text/javascript' nonce='<?= html_escape($cspNonce); ?>'";

Does anyone have an idea ?

sebfaed 2 months 0 Answers 16 views 0

Leave an answer