Search code examples
ruby-on-railsrubyrails-activestorage

link_to helper not showing "target" attribute in _blob.html.erb


I want to put target="_blank" attribute in a link into an Active Storage Blobs partial view (app/views/active_storage/blobs/_blob.html.erb), but attribute is not shown in final html.

#app/views/active_storage/blobs/_blob.html.erb

<%= link_to blob.filename, rails_blob_path(blob), target: "_blank" %>

In final HTML target="_blank" is not shown:

<a href="/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBDZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--48145f82f0b597246f7579fe56b06f563320fe15/file.pdf">file.pdf</a>

In fact, for testing, I put <a> HTML tag instead of link_to helper and doesn't work either. However, in another view it works.

I tested with ID attribute and doesn't work either.

Ruby version: ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x64-mingw-ucrt]

Rails version: Rails 7.0.6.

OS: Windows 11.

For your help thank you, very much


Solution

  • If you're rendering Action Text, then the HTML will be sanitized. The render_action_text_content helper method uses the Rails::Html::Sanitizer.safe_list_sanitizer and will strip out the target attribute by default.

    One way to test what is happening is to go into the Rails console and do this:

    content = ActionText::Content.new('<a target="_blank" href="my_url">my text</a>')
    helper.render_action_text_content(content)
     => "<a href=\"my_url\">my text</a>"
    

    To allow the target attribute, you could add this to an initializer and then restart your app:

    ActionText::ContentHelper.allowed_attributes << 'target'
    

    This will allow the target to get through:

    content = ActionText::Content.new('<a target="_blank" href="my_url">my text</a>')
    helper.render_action_text_content(content)
     => "<a target=\"_blank\" href=\"my_url\">my text</a>"
    

    Note that the reason that the target attribute is stripped out by default is to prevent against tabnabbing. See this post for more info on the related attacks and how you can use noreferrer in the rel attribute to prevent security issues if you do decide to allow the target attribute.