Skip to content

Commit

Permalink
Skip target attribute on links with anchors.
Browse files Browse the repository at this point in the history
  • Loading branch information
fnando authored and flavorjones committed Dec 31, 2024
1 parent 7627aca commit 527bc58
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/loofah/scrubbers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,9 @@ def initialize # rubocop:disable Lint/MissingSuper
def scrub(node)
return CONTINUE unless (node.type == Nokogiri::XML::Node::ELEMENT_NODE) && (node.name == "a")

node.set_attribute("target", "_blank")
href = node["href"]

node.set_attribute("target", "_blank") if href && href[0] != "#"

STOP
end
Expand Down
11 changes: 11 additions & 0 deletions test/integration/test_scrubbers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ class IntegrationTestScrubbers < Loofah::TestCase
TARGET_FRAGMENT = '<a href="http://www.example.com/">Click here</a>'
TARGET_RESULT = '<a href="http://www.example.com/" target="_blank">Click here</a>'

ANCHOR_TARGET_FRAGMENT = '<a href="#top">Click here</a>'
ANCHOR_TARGET_RESULT = '<a href="#top">Click here</a>'

TARGET_WITH_TOP_FRAGMENT = '<a href="http://www.example.com/" target="_top">Click here</a>'
TARGET_WITH_TOP_RESULT = '<a href="http://www.example.com/" target="_blank">Click here</a>'

Expand Down Expand Up @@ -203,6 +206,14 @@ def html5?
assert_equal TARGET_RESULT, doc.xpath("/html/body").inner_html
assert_equal doc, result
end

it "skips target attribute when linking to anchor" do
doc = klass.parse("<html><body>#{ANCHOR_TARGET_FRAGMENT}</body></html>")
result = doc.scrub!(:targetblank)

assert_equal ANCHOR_TARGET_RESULT, doc.xpath("/html/body").inner_html
assert_equal doc, result
end
end

context "when target is set" do
Expand Down

0 comments on commit 527bc58

Please sign in to comment.