Skip to content

Commit

Permalink
feature: iframe normalizer
Browse files Browse the repository at this point in the history
  • Loading branch information
spyderdfx committed Jul 6, 2017
1 parent 599dc3f commit 0f1be65
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
24 changes: 23 additions & 1 deletion lib/string_tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,14 +176,17 @@ def sanitize(str, attr = {})
attributes.merge!(attr)
elements = attributes.keys | TAGS_WITHOUT_ATTRIBUTES

transformers = [LINK_NORMALIZER]
transformers << IframeNormalizer.new(attributes['iframe']) if attributes.key?('iframe')

Sanitize.fragment(
str,
:attributes => attributes,
:elements => elements,
:css => {:properties => Sanitize::Config::RELAXED[:css][:properties]},
:remove_contents => %w(style javascript),
:allow_comments => false,
:transformers => [LINK_NORMALIZER]
:transformers => transformers
)
end
end
Expand Down Expand Up @@ -211,6 +214,25 @@ def normalize_link(node, attr_name)
end
end

class IframeNormalizer
def initialize(attributes)
@attributes = attributes
end

def call(env)
node = env[:node]

return unless node.name == 'iframe'

unless node[:src] =~ %r{^(http|https):?\/\/(www\.)?youtube?\.com\/}
node.unlink
return
end

Sanitize.node!(env[:node], elements: %w(iframe), attributes: {'iframe' => @attributes})
end
end

LINK_NORMALIZER = LinkNormalizer.new
end

Expand Down
11 changes: 11 additions & 0 deletions spec/string_tools_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@
sanitized_string = described_class.sanitize(origin_str)
expect(sanitized_string).to eq '<span>a</span><span>z</span>'
end

it 'removes iframes but keeps youtube' do
origin_str =
'<iframe width="20" height="10" src="https://www.dunno.com/embed/qwe" frameborder="0" allowfullscreen>' \
'</iframe>' \
'<iframe width="123" height="456" src="https://www.youtube.com/embed/abc" frameborder="0" allowfullscreen>' \
'</iframe>'
sanitized_string = described_class.sanitize(origin_str, 'iframe' => %w(src width height frameborder))
expect(sanitized_string).
to eq('<iframe width="123" height="456" src="https://www.youtube.com/embed/abc" frameborder="0"></iframe>')
end
end

describe '#clear_unicode_separator_characters' do
Expand Down

0 comments on commit 0f1be65

Please sign in to comment.