How to post-process HTML to add "target blank" to all links in Ruby?
Asked Answered
C

1

7

How to post-process HTML to add "target blank" to all links in Ruby?

I am currently using Rinku (gem) to auto-link text, and that works great.

However, I am post-processing HTML and some links are already links, and therefore are not processed with Rinku.

How could I add the target blank attribute to those?

application_controller.rb

def text_renderer text
  AutoHTML.new(text).render
end

auto_html.rb

class AutoHTML
  include ActionView::Helpers

  def initialize text
    @text = text
  end

  def render
    text = prepare @text
    text = auto_link(text)
    text.html_safe
  end

  private

  def prepare text
    if text.nil? || text.empty?
      ""
    else
      text
    end
  end

  def auto_link text
    Rinku.auto_link(text, :all, 'target="_blank"')
  end
end
Craniotomy answered 18/7, 2016 at 21:7 Comment(1)
For security reasons you might want to consider to not use target="_blank"...Mckelvey
I
7

I implemented a solution with nokogiri:

def self.a_with_target_blank(body)
  doc = Nokogiri::HTML(body)
  doc.css('a').each do |link|
    link['target'] = '_blank'
    # Worried about @spickermann's security concerns in the comment? then
    # consider also to add:
    # 
    # link['rel'] = 'noopener' 
    # 
    # In any case, this security hole has been solved in modern browsers, (check
    # https://github.com/whatwg/html/issues/4078) so unless you're supporting
    # very old browsers, there's no much to worry about.
  end
  doc.to_s
end
Intelligibility answered 9/1, 2017 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.