Would this method be of any use to you?
There is more information about this here too.
Hope this helps.
Thread Starter
Jonas
(@ropaeh)
Hey, unfortunately it didn’t really help me.
wp_localize_script allows me, as i understood it, to pass variables from php to js.
But i actually really just need a hook or function or whatever that enqueues a js script in the proper way and outputs it like <script nonce="herecomesthenonce" src="source"></script>
but so far i wasn’t able to get the nonce in there..
Thread Starter
Jonas
(@ropaeh)
I actually found a quite simple way to do this.
It’s possible via the “script_loader_tag” hook and a filter function.
The following code adds a nonce attribute, generated with the handle, to every enqueued script.
/** Add Nonce Attribute To Javascript **/
function add_nonce_attr( $tag, $handle, $src ) {
return '<script type="text/javascript" nonce="'.wp_create_nonce( $handle ).'" src="'.$src.'"></script>'."\n";
}
add_filter( 'script_loader_tag', 'add_nonce_attr', 10, 3 );
Note: the “script_loader_tag” hook is only available since Version 4.1.0
-
This reply was modified 5 years, 7 months ago by
Jonas.
-
This reply was modified 5 years, 7 months ago by
Jonas.
@ropaeh, thanks for that function! Can I ask how you inserted the nonces into your CSP from here?
Thanks!
Thread Starter
Jonas
(@ropaeh)
@jamesspi sure!
Can I ask how you inserted the nonces into your CSP from here?
That’s the next problem i’m facing right now. Because the wp_create_nonce() function depends on the time of the day, it changes every now and then. I’m thinking of writing all generated nonces in an array and adding them to the CSP via php’s header function. But i haven’t tried it so far.