2

Here is my script for testing purposes

<script>
var json = {
     "html": "<h3>COVID-19 Visitor Declaration</h3><script></script>"
};
</script>

That will throw a javascript error

Uncaught SyntaxError: Invalid or unexpected token

Now if I change the script to something else the error goes away

<script>
var json = {
     "html": "<h3>COVID-19 Visitor Declaration</h3><scripta></scripta>"
};
</script>

How can I let that script tag go through as valid JSON, guessing this is something to do with security.

rukiman
  • 597
  • 10
  • 32
  • its not json, its an object literal. https://stackoverflow.com/q/28259389/17447 – naveen Feb 10 '21 at 06:55
  • 1
    thanks that made sense, so real issue is that the html parser gets confused when it sees the script although it is in a string. Interesting. – rukiman Feb 10 '21 at 06:58

2 Answers2

2

You have to update your code to:

<script>
    var json = {
        "html": "<h3>COVID-19 Visitor Declaration</h3><script><\/script>"
    };
</script>

Escaped tag </script> is most important for that.

VirCom
  • 3,414
  • 1
  • 10
  • 10
  • But then why does the work? – rukiman Feb 10 '21 at 06:48
  • 1
    Because it doesnt get interpreted as script? @rukiman As soon as you put up script tags, your browser expects javascript. Using a different tag like is nothing different than using an image tag for example. its not "reserved" – Aaron Feb 10 '21 at 06:52
0

By using the Escape characters, for your closing tag <\/script>

var json = {
  "html":  "<h3>COVID-19 Visitor Declaration</h3><script><\/script>"
};


document.getElementById("html-content").innerHTML = json.html;
<div id="html-content"></div>

<scripta> works because it's not a valid tag for the browsers to evaluate and thus render it as normally on DOM.

When you pass <script>, browser parse it a valid HTML tag

var json = {
  "html":  "<h3>COVID-19 Visitor Declaration</h3><scripta>Test</scripta>"
};


document.getElementById("html-content").innerHTML = json.html;
<div id="html-content"></div>
Not A Bot
  • 2,474
  • 2
  • 16
  • 33