Intensive Programmer

技術的なことや読書感想などなど...

【webkit】画面真っ白になる

@suzukai74です。

Railsでプレビュー画面実装時にChromeSafariでページの要素が全て吹っ飛んで、真っ白になるという問題がありました。

実装

実装は以下のようなカンジで、プレビュー時にプレビュー用のテンプレートを表示させています。

def update
  @article = Article.find(params[:id])
  @article.attributes = article_params

  if preview?
    render "preview"
  end

  if @article.save
    redirect_to action: index
  else
    render :edit
  end
end

private

  def article_params
    params.require(:article).permit(:body)
  end

  def preview?
    params.key?('preview')
  end

プレビュー画面を開くと真っ白画面になる

f:id:suzukai74:20161206160848p:plain

ちなみに中身のhtmlは

<html>
  <head></head>
  <body cz-shortcut-listen="true">
    <pre style="word-wrap: break-word; white-space: pre-wrap;"></pre>
  </body>
</html>

見事に何もない!!

原因

原因はwebkitXSS(クロスサイトスクリプティング)対策でした。
今回の実装ではtextareaにscriptタグもかけるようにしているため、外部ファイル等を読み込んでいると
無効化されてしまうという問題でした。
webkit系のブラウザはヘッダーにX-XSS-Protection:1; mode=block
が設定されていると無効化されてしまいます。

RailsはデフォルトでX-XSS-Protection:1; mode=blockが設定されます。
railsguides.jp

回避策

X-XSS-Protectionに0を設定してあげれば無効化されずに表示されます。

def update
  @article = Article.find(params[:id])
  @article.attributes = article_params

  if preview?
    remove_xss_protection
    render "preview"
  end

  if @article.save
    redirect_to action: index
  else
    render :edit
  end
end

private

  def article_params
    params.require(:article).permit(:body)
  end

  def preview?
    params.key?('preview')
  end
  
  def remove_xss_protection             
    response.headers['X-XSS-Protection'] = "0"
  end


ページ作成のプレビューやiframeなどでは外部リソースを読み込む際には気をつけましょう。
ブラウザチェック大切ですw