instance method sanitize

Ruby on Rails 3.2.22.5

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

sanitize(html, options = {})

This sanitize helper will html encode all tags and strip all attributes that aren’t specifically allowed.

It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters. Check out the extensive test suite.

<%= sanitize @article.body %>

You can add or remove tags/attributes if you want to customize it a bit. See ActionView::Base for full docs on the available options. You can add tags/attributes for single uses of sanitize by passing either the :attributes or :tags options:

Normal Use

<%= sanitize @article.body %>

Custom Use (only the mentioned tags and attributes are allowed, nothing else)

<%= sanitize @article.body, :tags => %w(table tr td), :attributes => %w(id class style) %>

Add table tags to the default allowed tags

class Application < Rails::Application
  config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
end

Remove tags to the default allowed tags

class Application < Rails::Application
  config.after_initialize do
    ActionView::Base.sanitized_allowed_tags.delete 'div'
  end
end

Change allowed default attributes

class Application < Rails::Application
  config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style'
end

Please note that sanitizing user-provided text does not guarantee that the resulting markup is valid (conforming to a document type) or even well-formed. The output may still contain e.g. unescaped ‘<’, ‘>’, ‘&’ characters and confuse browsers.

Parameters

html req
options opt = {}
Source
# File actionpack/lib/action_view/helpers/sanitize_helper.rb, line 59
      def sanitize(html, options = {})
        self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe)
      end

Defined in actionpack/lib/action_view/helpers/sanitize_helper.rb line 59 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::SanitizeHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close