How to ensure that an opaque block of JavaScript or CSS can be safely embedded within an HTML or tag? [duplicate]

1 day ago 2
ARTICLE AD BOX

Suppose I have an opaque block of script or style data, which I want to embed inside a <script> or <style> tag in an HTML file, such that it will be interpreted with the exact same meaning.

In XHTML, the solution would have been easy: put the contents inside a <![CDATA[…]]> block (and watch out for any embedded ]]>), or use predefined XML entities &lt; and &amp; to represent < and & (since outside attribute values, one can probably get away with not using &gt;, &quot; and &apos;).

In HTML syntax, this is not as easy.

<!-- should have been: console.log("<\/script>"); --> <script>console.log("&lt;/script>");</script> <!-- should have been: console.log("foo" < /script>/); --> <script>console.log("foo"&lt;/script>/);</script> <!-- should have been: ????? 🐘×🦏 --> <script>console.log(function() { /* &lt;/script> */ }.toString());</script> <script>console.log(String.raw`&lt;/script>`);</script>

Is there any way to escape the contents of a <script> or <style> tag, other than tokenizing it and substituting semantically (although not lexically) equivalent constructs, if they exist?

Read Entire Article