Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 971
alejorivera Avatar asked Jul 18 '16 21:07

alejorivera


People also ask

How do I add a target blank in HTML?

You can use the target="_blank" attribute if you want your users to click on a link that opens up a new browser tab. The target="_blank" attribute is used inside the opening anchor tag like this.

How do you add a target _blank to a URL?

Select the outer DIV element of anchor element. Use . attr() method to set the target property to “_blank” of the anchor element.

What does the _blank attribute in HTML links do?

A target attribute with the value of “_blank” opens the linked document in a new window or tab. A target attribute with the value of “_self” opens the linked document in the same frame as it was clicked (this is the default and usually does not need to be specified).

When should the target _blank attribute be used in a hyperlink?

One of the possible values of that attribute is _blank , which tells the browser to open a new window (or tab, if that's the user's preference) when that link is clicked. This used to be “invalid” in HTML (maybe only XHTML?) but people used it anyway since it worked. It's now perfectly valid in HTML5.


1 Answers

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
like image 103
Alter Lagos Avatar answered Sep 30 '22 06:09

Alter Lagos