1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsでインラインJSが動作しなくなったときの対応

Posted at

RailsでインラインJSを書くと下記エラーで動作しなくなりました:frowning2:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' https:". Either the 'unsafe-inline' keyword

原因は、Ruby on Rails 5.2の新機能にContent Security Policyが追加されたことでした。
デフォルトの設定のままではインラインJSが動作しないので
content_security_policy.rbファイルのpolicy.script_src:unsafe_inlineをつけることが必要になります。

content_security_policy.rb
policy.default_src :self, :https
policy.font_src    :self, :https, :data
policy.img_src     :self, :https, :data
policy.object_src  :none
policy.script_src  :self, :https, :unsafe_inline
policy.style_src   :self, :https, :unsafe_inline

今回はrailsからJS側にデータ渡す必要があったため、インラインJSをやむを得ず使いましたが、
極力はJSファイルを読み込むように気をつけたいですね:relaxed:

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?