Search code examples
ruby-on-railsimagesanitizedata-uri

How to enable embedded image in rails sanitize?


I would like to use embedded images in rails, like this:

<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />

In my view I use sanitize to filter html tags, like this:

sanitize @post.body,
         tags: %w(h1 h2 span code a img pre strong u em s sub sup ol li ul blockquote),
         attributes: %w(class style href width height src alt)

As you can see I enable img element and src attribute, but sanitize filters out src attribute in case of embedded images (data URI scheme). In case of "normal" images (where src is a normal link), it works correctly.

How can I tell sanitize to enable embedded images?


Solution

  • The solution is to enable data protocol with the following code:

    HTML::WhiteListSanitizer.allowed_protocols << 'data'
    

    I use it in config/initializers/sanitize.rb , and now it works for me.