LoginSignup
4
8

More than 3 years have passed since last update.

Railsでiframeを使いたい

Last updated at Posted at 2019-12-18

やりたいこと

・Railsでiframeからのリクエストを許可して外部のサイトで表示させたい
・すべて許可するとなにかと怖いので特定のURLに絞りたい

ということで

Railsでは

response.headers['X-Frame-Options'] = 'SAMEORIGIN'

が設定されていて自身のドメインしかiframeで表示出来ないそう

今回は特定のURLのみ許可したいので以下のように実装

class HogeController < ApplicationController
    after_action :allow_iframe, only: [:hoge]

    def hoge
        render "hoges/index", layout: false
    end

    private
    def allow_iframe
        url = "https://hoge.com"
        response.headers['X-Frame-Options'] = "ALLOW-FROM #{url}"
        response.headers['Content-Security-Policy'] = "frame-ancestors #{url}"
    end
end

注意点

なんと皆がよく使ってるであろうChrome、Safariなど多くのブラウザが
X-Frame-Options ALLOW-FROM
に対応していません1

なので合わせて
Content-Security-Policy frame-ancestors
も記述してやりましょう2

調べてみた感じIE以外対応してたので安心です3

効いてるか確認

Chrome DevToolsのNetwork パネルで確認できます
C__でなにができるの?おススメ案件!___ITフリーランスエンジニアのためのコラム【at-engineer】.png


  1. X-Frame-Options ブラウザ対応表 

  2. X-Frame-Options ALLOW-FROMだけ設定してしまうと未対応ブラウザですべてのURLを許可する状態になってしまいます 

  3. Content-Security-Policyブラウザ対応表 

4
8
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
4
8