方法
執行個體公有方法
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 中的檔案,HTTP 狀態碼為「406 Not Acceptable」。
除了明確命名的瀏覽器版本外,您還可以傳遞 :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
原始碼:顯示 | 於 GitHub 上
# 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