A variable string that causes the browser to crash

I found something very strange. When you post something like this on your html page, the browser (tested on FF and Chrome) just stops displaying the page in this place:

<script type="text/javascript"> // var Crash = "<!--<SCRIPT>"; </script> 

Obviously, you can also:

  <script type="text/javascript"> var Crash = "<!--<SCRIPT>"; </script> 

Or:

  <script type="text/javascript"> var Crash = "<!-- WHATEVER YOU WANT HERE <SCRIPT>"; </script> 

Any ideas why this is happening?

+8
javascript browser
source share
2 answers

TL; DR:

Do not do this - this forces the parser to follow some strange rules about double-shielding script data, leaving it in the β€œwrong” state (from your point of view) by the time it reaches </script> . There are ways to avoid events in your script data , to make sure that they will behave the way you want, without breaking the parsing.


The analyzer has a strict set of rules that follows when analyzing the page. In this case:

So now we are in a state where the browser thinks it is still in some escaped script data, instead of the original <script> being closed, so any further HTML is not considered as such - it still thinks this script data that is passed to the script engine rather than processed as HTML.

The reasons for the parser working this way are not clear, but over time the situation has changed, probably due to some terrifying reasons for backward compatibility.

+5
source share

In the past, it was common to handle browsers that did not know the script tag by adding html comments in script blocks:

 <script language="javascript"> <!-- // code here //--> </script> 

As you can see, the first <!-- invalid in javascript, but still browsers must ignore it in order to be compatible with this old trick. This seems to cause strange behavior in some browser when we add <script> , as you can see in this script: https://jsfiddle.net/bjeLh5Ln/

So, you need to either close the html comment by adding // --> to your script, or paste </script> twice.

+3
source share

All Articles