Because of Content-Security-Policy (CSP) my inline <script>
tags will be blocked if they don't contain a nonce=" ... "
variable. I create the $nonce variable in PHP with the built in Wordpress method at the top of my template:
<?php $nonce = wp_create_nonce( 'secret-for-inline-js' ); ?>
Then I evaluate the script tags' nonce value in my html to allow it to be echoed into the output by php. This works for all but two scripts that are located in two wp-blocks of the Plain HTML type in the page editor.
<?php
if ( ! wp_verify_nonce( $nonce, 'secret-for-inline-js' ) ) {
die( __( 'You cannot do that', 'textdomain' ) );
} else { ?>
<script nonce="<?php echo $nonce ?>"> // JS goes here
</script>
<?php } ?>
The codeblocks in the editor load JS scripts with config for Chart.js (the chart library loads correctly from an external source I explicit authorize in the CSP). The client wants to edit the charts, so it has to be like this. I need to add the nonce variable to the script tags here, too because I cannot use the 'unsafe-inline'
value for script-src in the CSP (because it contradicts the whole point of using CSP).
I'm aware of different methods to read the PHP variable in html or javascript and methods to pass it into the script tags, like these:
How do I pass variables and data from PHP to JavaScript?
However, I cannot do this because the script tag isn't a typical external javascript loaded via the Wordpress functions.php
setup. I cannot use PHP because it's not supported by the editor (and I cannot use a PHP plugin to allow editor php because of safety measures).
So I wonder if there's a workaraound to get a variable into <script nonce="variable_here">
while read from the WP editor.
My only idea so far is to add a class/id to these two script tags and target them with JS after they have been read by html, and then change the content of the script tag (but I'm not sure if this would actually make it run and load chart.js). I don't see a way to wrap everything in a JS function that forces execution of what's inside, because this script would also need the nonce parameter to run...!
Thanks for your suggestions.