diff --git a/lib/loofah/scrubbers.rb b/lib/loofah/scrubbers.rb index 9dd8869..63d3aec 100644 --- a/lib/loofah/scrubbers.rb +++ b/lib/loofah/scrubbers.rb @@ -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 diff --git a/test/integration/test_scrubbers.rb b/test/integration/test_scrubbers.rb index b9401b6..d7665be 100644 --- a/test/integration/test_scrubbers.rb +++ b/test/integration/test_scrubbers.rb @@ -19,6 +19,9 @@ class IntegrationTestScrubbers < Loofah::TestCase TARGET_FRAGMENT = 'Click here' TARGET_RESULT = 'Click here' + ANCHOR_TARGET_FRAGMENT = 'Click here' + ANCHOR_TARGET_RESULT = 'Click here' + TARGET_WITH_TOP_FRAGMENT = 'Click here' TARGET_WITH_TOP_RESULT = 'Click here' @@ -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("#{ANCHOR_TARGET_FRAGMENT}") + 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