如何替换渲染内联:“<script> window.location.replace('#{url}')</script>”for Rails 5.2

时间:2018-01-11 03:24:58

标签: javascript ruby-on-rails

这部分应用程序在ruby 2.4.6和rails 4.2.6中工作:

def refresh_to(url='/', option={})
  if option[:alert]
    ma_log option[:alert]
  end
  render inline: "<script>window.location.replace('#{url}')</script>"
end

但是在ruby 2.5和Rails 5.2中,不再允许这样做了。我收到了错误:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' https:". Either the 'unsafe-inline' keyword, a hash ('sha256-myVzA8nG9TALJ+lM9KxIly4S3wxH68o0ybnPpqphBBg='), or a nonce ('nonce-...') is required to enable inline execution.

the previous related errors的解决方案无效。

如何编写或管理脚本,以便在使用或不使用render的情况下使用(或替换)inline?我正在探索在/assets/javascript中添加一个脚本。你是怎么做到的?

编辑。

Refused to execute inline script because it violates the following 
Content Security Policy directive: "script-src 'self' https:". Either 
the 'unsafe-inline' keyword, a hash ('sha256-
myVzA8nG9TALJ+lM9KxIly4S3wxH68o0ybnPpqphBBg='), or a nonce 
('nonce-...') is required to enable inline execution.

Content Security Protocol开始,内联脚本不再支持。 (在升级到rails 5.2所有内联(#)脚本错误时发生)。 包括嵌入式内嵌js:

      #render inline: "<script>window.location.replace('#{url}')</script>"
      render js: "window.location.replace(\'#{url}\')" 

错误:

ActionController::InvalidCrossOriginRequest at /logout
Security warning: an embedded <script> tag on another site requested 
protected JavaScript. If you know what you're doing, go ahead and 
disable forgery protection on this action to permit cross-origin 
JavaScript embedding.

来自:关于protect_from_forgery(options = {})的文件。当我在ApplicaitonController中包含选项时,无法使用Rails 5.2 Beta

class ApplicationController < ActionController::Base
  skip_before_action :refresh_to, raise: false

所以:以下类型的内联代码需要重写

render inline: "<script>window.location.replace('#{url}')</script>"

我将尝试使用几个版本的rails进行测试,但如果有人可以免费使用您的代码,我将不胜感激。

编辑。

seperat javascript的另一个试验

创建/app/assets/javascript/refresh.js

function refresh() {
  window.location.replace('/')
}

-In控制器方法使用render js:“refresh.js”

def refresh_to(url='/', option={})
  if option[:alert]
    ma_log option[:alert]
  end
#render inline: "<script>window.location.replace('#{url}')</script>"
#render js: "window.location.replace(\'#{url}\')" 
render js: "refresh();"

结果:不行!关于C.S.P的相同错误

  

我的上一个问题:How to pass parameter(url) to refresh.js ?

0 个答案:

没有答案