Adding nonce to <script> tag

不想你离开。 提交于 2021-02-08 07:07:17

问题


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,
) );`

And I want to have something like this:

<script nonce="nonce-value">...</script>

Where nonce-value is random.

This only one of places where I need this, is there any idea how to add it globally to <script> tag?


回答1:


Haven't tested this, but Wordpress does provide a script_loader_tag filter which allows you to modify the generated script tags from enqueued scripts.

add_filter( 'script_loader_tag', 'add_nonce_to_script', 10, 3 );

function add_nonce_to_script( $tag, $handle, $src ) {
    global $my_nonce;
    return '<script type="text/javascript" src="' . esc_url( $src ) . '" nonce="' . esc_attr( $my_nonce ) . '"></script>';
}



回答2:


Try this code,

add_filter('script_loader_src','add_nonce_to_script',10,2);
function add_nonce_to_script($src, $handle){
   $my_nonce = wp_create_nonce('nonce-'.rand());
   return $src.' nonce= '.$my_nonce;
}

Hope this will helps you. For more example,

Adding Additional Attributes in Script Tag




回答3:


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 ); 

}

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.



来源:https://stackoverflow.com/questions/50002041/adding-nonce-to-script-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!