跳至内容 跳至搜索
方法
A

实例公共方法

allow_browser(versions:, block: -> { render file: Rails.root.join("public/406-unsupported-browser.html"), layout: false, status: :not_acceptable }

指定允许访问所有操作(或通过 only:except: 限制的某些操作)的浏览器版本。如果名称与 versions: 中哈希表或命名集匹配的浏览器版本低于指定的版本,它们将被阻止。这意味着所有其他浏览器以及未报告用户代理头的代理都将被允许访问。

默认情况下,被阻止的浏览器将获得 public/406-unsupported-browser.html 文件,并附带“406 Not Acceptable”的 HTTP 状态码。

除了专门命名的浏览器版本外,您还可以传递 :modern 作为集合,将支持限制为原生支持 webp 图像、Web 推送、徽章、导入映射、CSS 嵌套和 CSS :has 的浏览器。这包括 Safari 17.2+、Chrome 120+、Firefox 121+、Opera 106+。

您可以使用 caniuse.com 来检查支持您使用的功能的浏览器版本。

您可以使用 ActiveSupport::Notifications 通过 browser_block.action_controller 事件名来订阅浏览器被阻止的事件。

示例

class ApplicationController < ActionController::Base
  # Allow only browsers natively supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has
  allow_browser versions: :modern
end

class ApplicationController < ActionController::Base
  # Allow only browsers natively supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has
  allow_browser versions: :modern, block: :handle_outdated_browser

  private
    def handle_outdated_browser
      render file: Rails.root.join("public/custom-error.html"), status: :not_acceptable
    end
end

class ApplicationController < ActionController::Base
  # All versions of Chrome and Opera will be allowed, but no versions of "internet explorer" (ie). Safari needs to be 16.4+ and Firefox 121+.
  allow_browser versions: { safari: 16.4, firefox: 121, ie: false }
end

class MessagesController < ApplicationController
  # In addition to the browsers blocked by ApplicationController, also block Opera below 104 and Chrome below 119 for the show action.
  allow_browser versions: { opera: 104, chrome: 119 }, only: :show
end
# File actionpack/lib/action_controller/metal/allow_browser.rb, line 57
def allow_browser(versions:, block: -> { render file: Rails.root.join("public/406-unsupported-browser.html"), layout: false, status: :not_acceptable }, **options)
  before_action -> { allow_browser(versions: versions, block: block) }, **options
end