admin管理员组

文章数量:1173665

Hooking into the script_loader_tag hook and generating random strings is no problem, but how can I generate them once per page load and use them in both wp_head and script_loader_tag?

I'd really like to upgrade my CSP, but all the plugins I've found to do it mangle minification.

Hooking into the script_loader_tag hook and generating random strings is no problem, but how can I generate them once per page load and use them in both wp_head and script_loader_tag?

I'd really like to upgrade my CSP, but all the plugins I've found to do it mangle minification.

Share Improve this question edited Jul 20, 2018 at 3:02 Castiblanco 2,1947 gold badges20 silver badges26 bronze badges asked Jul 20, 2018 at 2:58 SlboxSlbox 1098 bronze badges 2
  • edit your question to show the code you tried. – mmm Commented Jul 20, 2018 at 4:59
  • I can't come up with any reasonably clean code that could possibly work, so I've tried no code. – Slbox Commented Jul 20, 2018 at 15:59
Add a comment  | 

2 Answers 2

Reset to default 1

Actually, you would not use the wp_head action. That happens in the head part of the HTML output. To send a Content-Security-Policy header, or modify an existing one, you would want to hook into the wp_headers filter instead.

As for generating the nonce, you don't want to use a WordPress based nonce, as those are not unique per page load. You will want each load to have a random number generated.

As for using the same number in the wp_headers and the script_loader_tag, well, you just, you know, use the same number in both places. Generate the number in the body of your plugin code, put it in a global variable, then reference that variable from both functions hooked to those filters.

WP's nonces aren't true nonces as they are valid for about 24 hours. So, if you use the same string in wp_create_nonce( $action ) then WP will always generate the same nonce for a 24 hour period.

本文标签: