Skip to content

Commit 9601ac9

Browse files
committed
Ensure JSON.parse() errors don't interrupt parsing HTML
1 parent f81b606 commit 9601ac9

2 files changed

Lines changed: 19 additions & 6 deletions

File tree

src/trix/models/html_parser.coffee

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ class Trix.HTMLParser extends Trix.BasicObject
111111

112112
processElement: (element) ->
113113
if nodeIsAttachmentElement(element)
114-
attributes = getAttachmentAttributes(element)
114+
attributes = parseTrixDataAttribute(element, "attachment")
115115
if Object.keys(attributes).length
116116
textAttributes = @getTextAttributes(element)
117117
@appendAttachmentWithAttributes(attributes, textAttributes)
@@ -212,9 +212,8 @@ class Trix.HTMLParser extends Trix.BasicObject
212212
attributes[attribute] = value
213213

214214
if nodeIsAttachmentElement(element)
215-
if json = element.getAttribute("data-trix-attributes")
216-
for key, value of JSON.parse(json)
217-
attributes[key] = value
215+
for key, value of parseTrixDataAttribute(element, "attributes")
216+
attributes[key] = value
218217

219218
attributes
220219

@@ -237,8 +236,11 @@ class Trix.HTMLParser extends Trix.BasicObject
237236
element = element.parentNode
238237
ancestors
239238

240-
getAttachmentAttributes = (element) ->
241-
JSON.parse(element.getAttribute("data-trix-attachment"))
239+
parseTrixDataAttribute = (element, name) ->
240+
try
241+
JSON.parse(element.getAttribute("data-trix-#{name}"))
242+
catch
243+
{}
242244

243245
getImageDimensions = (element) ->
244246
width = element.getAttribute("width")

test/src/unit/html_parser_test.coffee

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,17 @@ testGroup "Trix.HTMLParser", ->
192192
expectedHTML = """<div><!--block-->a b c</div>"""
193193
assert.documentHTMLEqual Trix.HTMLParser.parse(html).getDocument(), expectedHTML
194194

195+
test "ignores attachment elements with malformed JSON", ->
196+
html = """
197+
<div>a</div>\
198+
<div data-trix-attachment data-trix-attributes></div>\
199+
<div data-trix-attachment="" data-trix-attributes=""></div>\
200+
<div data-trix-attachment="{&quot;x:}" data-trix-attributes="{&quot;x:}"></div>\
201+
<div>b</div>
202+
"""
203+
expectedHTML = """<div><!--block-->a</div><div><!--block--><br></div><div><!--block-->b</div>"""
204+
assert.documentHTMLEqual Trix.HTMLParser.parse(html).getDocument(), expectedHTML
205+
195206
test "parses attachment caption from large html string", (done) ->
196207
html = fixtures["image attachment with edited caption"].html
197208

0 commit comments

Comments
 (0)