LoginSignup
0
1

WordPressでiframeを埋め込んだらCSPエラーが発生した件

Last updated at Posted at 2024-05-27

はじめに

WordPressで作成したページにVimeoの動画を埋め込んだ際にContent Security Policy (CSP) エラーが発生したので、今回はそれについてまとめる。
CSPはセキュリティ対策の一環として重要だが、設定ミスや外部リソースの許可を適切に行わないとエラーが発生する。

問題点

以下のようなコードを追加して、Vimeoの動画を埋め込んだところ、以下のようなCSPエラーが発生しました。

<div class="main__video-item">
  <div style="padding:56.25% 0 0 0;position:relative;">
    <iframe src="https://player.vimeo.com/video/{video_id}?h={hash_parameter}" width="{video_width}" height="{video_height}" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;" title="〇〇"></iframe>
  </div>
  <script src="https://player.vimeo.com/api/player.js"></script>
</div>

発生したエラー:

[Report Only] Refused to load the script 'https://***' because it violates the following Content Security Policy directive: "script-src 'none'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

このエラーの原因は外部スクリプトの読み込みがCSPポリシーによりブロックされているためである。この問題を解決するためには、以下の手順でCSPポリシーを適切に設定する必要がある。

解決策

functions.phpに以下のコードを追加して、Vimeoのスクリプトを許可するCSPポリシーを設定する。

// functions.php に追加するコード
function add_custom_csp_policy() {
    header("Content-Security-Policy: default-src 'self'; script-src 'self' https://player.vimeo.com https://f.vimeocdn.com 'unsafe-inline'; frame-src https://player.vimeo.com;");
}
add_action('send_headers', 'add_custom_csp_policy');

このコードは、https://player.vimeo.comhttps://f.vimeocdn.com からのスクリプトを許可し、Vimeoの動画が正しく埋め込まれるようにします。

終わりに

今回は、WordPressでVimeoの動画を埋め込む際に発生するCSPエラーの解決方法についてまとめた。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1