[wp]CSP対応のjQueryライブラリ設置メモ

ちょっとの手間でなんとか。

要するに

  • wp既存のjQuery読み込み無効化
  • deferとnonceつける

wp既存のjQuery読み込み無効化

読み込み位置がまずいせいでjQueryが原因のエラーが解消しない。「あれだったら’unsafe-inline’を使え」ってメッセージがあるから入れても変わらない。ということで、無効化して自前で入れる。記述位置さえ変えられたらそれでいいんだけどね。

加えて、jQueryプラグイン周りのスクリプトも含めてインラインに対応するためにdeferとnonceを仕込む。

<?php
//WPデフォルトjQueryライブラリを読み込ませない
function delete_jquery() {
    if(is_admin()) return;
    wp_deregister_script('jquery');
}
//jQueryライブラリ読み込み
add_action('init', 'delete_jquery');
function add_headFiles() {
    if(is_admin()) return;
    if(!($_SESSION['no_commonsetting'] == true)):
        wp_enqueue_script('jQuery', 'https://code.jquery.com/jquery-3.6.1.js', array());
    endif;
}
//deferとnonceを追加
add_action('after_setup_theme', function(){
    if(is_admin()) return;
    ob_start(function ($buffer_html) {
        $nonce = wp_create_nonce( 'content-security-policy' );
        $buffer_html = str_replace('<script', '<script defer nonce="'.$nonce.'"', $buffer_html);
        $buffer_html = str_replace('<style', '<style nonce="'.$nonce.'"', $buffer_html);
        return $buffer_html;
    });
}, 90000);}

jQueryのCSPはオリジンとnonceが入ってればいいので、こんな感じで。

script-src https://code.jquery.com 'nonce-****';

そんな感じで。

コメント

タイトルとURLをコピーしました