将 nonce 添加到 <script>标签 [英] Adding nonce to <script> tag
问题描述
我想知道如何向基于 WordPress 的页面上的所有 <script>
标签添加随机数.例如,请在下面找到一些代码:
I'm wondering how to add nonce to my all <script>
tags on page based on WordPress. For example please find some code below:
$my_nonce = wp_create_nonce('nonce-'.rand());
$nonces = "Content-Security-Policy: script-src 'self nonce-".$my_nonce."'";
header( "{$nonces}");
wp_localize_script( 'my_loadmore', 'my_loadmore_params', array(
'ajaxurl' => site_url() . '\/wp-admin\/admin-ajax.php',
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
) );`
我想要这样的东西:
<script nonce="nonce-value">...</script>
其中 nonce-value 是随机的.
这只是我需要它的地方之一,有什么想法如何将它全局添加到 标签?
This only one of places where I need this, is there any idea how to add it globally to <script>
tag?
推荐答案
我在 functions.php 中设置了一个函数,以使用内置的 wordpress 函数生成随机数.
I setup a function in functions.php to generate a the nonce using the built wordpress function.
add_action( 'run_custom_nonce_value', 'custom_nonce_value' );
function custom_nonce_value () {
$created_nonce = wp_create_nonce();
define( 'NONCE_RANDVALUE', $created_nonce );
}
然后我设置这个过滤器以将 nonce 值添加到所有脚本
Then I setup this filter to add the nonce value to all of the scripts
add_filter( 'script_loader_tag', 'add_nonce_to_script', 10, 3 );
function add_nonce_to_script( $tag, $handle, $source ) {
custom_nonce_value();
$val_nonce = NONCE_RANDVALUE;
$search = "type='text/javascript'";
$replace = "type='text/javascript' nonce='".$val_nonce."' ";
$subject = $tag;
$output = str_replace($search, $replace, $subject);
return $output;
}
此解决方案会将随机数添加到所有正确注册的脚本中.
This solution will add the nonce to all correctly registered scripts.
这篇关于将 nonce 添加到 <script>标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!