The argument that JSON.stringify
may not always be secure in HTML attributes when the text is part of the HTML markup itself holds merit. However, there are no escaping concerns if utilizing access methods like .data
or .attr
to set the value as they do not directly alter raw HTML content.
While using encodeURIComponent
could technically solve the issue by escaping problematic characters, it leads to unsightly values/markup and requires manual decoding with decodeURIComponent
when consuming the data - not ideal!
Instead of directly inserting data into HTML, encode the value for HTML and use the encoded result as the attribute value. Most server-side languages offer a function for this purpose, though JavaScript does not provide an equivalent natively.
If attribute values are enclosed in quotes, certain characters must be replaced with their corresponding HTML entities:
&
- &
, escape-the-escape, should be applied first
"
- "
, for double-quoted attributes
'
- '
, for single-quoted attributes
- Optional (required for XML):
<
and >
This approach relies on parsing the HTML markup and automatically decoding HTML entities within it, ensuring that the actual (non-encoded) data is stored as the value of the data attribute in the DOM.