Ryszard Bosiak
Ryszard Bosiak

Reputation: 75

Adding nonce to <script> tag

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?

Upvotes: 4

Views: 6455

Answers (3)

Robbiegod
Robbiegod

Reputation: 1014

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.

Upvotes: 1

Sunil Dora
Sunil Dora

Reputation: 1472

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

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

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>';
}

Upvotes: 1

Related Questions