• Resolved timholz

    (@timholz)


    Hi – Since the Content Security Policy directives for sript-src are somehow contradictory (unsafe-inline) and google PageSpeed insights recommends to add a nonce value, i wonder if it is possible to add a nonce value for the optimized and aggregated scripts?
    I tried the following:

    function add_nonce($tag, $handle, $src) {
        $nonce_value = wp_create_nonce('my__script__nonce');
        return "<script defer='defer' nonce='".$nonce_value."' src='".$src."'></script>";//Usually the value in $tag variable looks similar to this script tag but without the async and defer
    }
    add_filter('script_loader_tag', 'add_nonce', 10, 2);

    This works, but it prevents the aggregation of all scripts.
    Is there a valid way to add a nonce attribute to aggregated script?
    Is there a filter to capture the moment when aggregation happens and inject a nonce attribute?
    Thanks for a feedback.
    regards – theo

    • This topic was modified 3 years, 6 months ago by timholz.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Optimizing Matters

    (@optimizingmatters)

    You could probably use the autoptimize_filter_js_bodyreplacementpayload for that Theo, adding the nonce after <script using str_replace.

    hope this helps,
    frank

    Thread Starter timholz

    (@timholz)

    Thanks for your advice. I’ll try that and will report later.
    theo

    Thread Starter timholz

    (@timholz)

    This seems to work so far:

    //nonce for aggregated scripts
    function add_nonce($bodyreplacementpayload){
        $nonce_value = wp_create_nonce('my_script_nonce');
        $find = '<script ';
        $replacement = '<script nonce="'.$nonce_value.'"';
        $string = $bodyreplacementpayload;
        $addnonce = str_replace($find, $replacement, $string);
        return $addnonce;
    }
    add_filter('autoptimize_filter_js_bodyreplacementpayload', 'add_nonce');

    I will have to test its effect on CSP. For now, thanks for your suggestion.
    regards – theo

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘PageSpeed insights recommends a nonce value for safe CSP’ is closed to new replies.