alert("Hello")

Script tag rules

Consider the following html document:

<!DOCTYPE html> <html> <head> <script type="text/javascript"> alert("Hello") </script> </head> </html> 

The result of opening in Firefox, Safari, and Chrome on my macbook is the same: "Hello" is displayed in the warning message. I read this answer to try to understand the behavior of browsers. Main part:

Since the content of tags is treated as CDATA, the content is not parsed, and you can store unspecified XML or HTML in the content (if you never put the </script> in the content, as this will close your element).

Let's try what happens when we see the source in Firefox:

source code screenshot with </script> in the alert call

The output in the browser that it shows is ") , because it believes that the script tag has been closed inside the alert. One way to overcome this is if we really want to display "</script>" :

 <!DOCTYPE html> <html> <head> <script type="text/javascript"> alert("<"+"/script>") </script> </head> </html> 

Firefox now understands this:

source code screenshot with "</" + "script>" in the alert call

Question:

It's really easy for the parser to check if </script> closing part. It takes more time to verify this, but it is doable (count the number of quotes before the meeting </script> . If even then it is a closing tag, otherwise continue searching for a closing tag). The question is, is it a rule that we cannot write "</script>" inside javascript? If so, what other subtle rules exist there that I may not have suspected?

The same can be said of php parsers. <?php echo "?>" ?> . I checked this, and php seems to know where the real one is located ?> .

+4
source share
1 answer

That's right, you cannot write "</script>" inside the built-in Javascript, but you can write "<\/script>" . In an external Javascript file, you do not have this restriction.

The Javascript engine will see "</script>" as the end of the script, regardless of context.

As long as you use HTML, not XHTML, this is the only real version.

XHTML, which was used as the XHTML file . [1] has a few more fixes, including -- - the beginning and end of the XHTML comment.

[1] Very little XHTML material is actually served by XHTML. It usually served as HTML, and then was processed by a parser for soup tags, which could understand all of the embedded HTML comments and even CDATA tags that do not belong.

+4
source

Source: https://habr.com/ru/post/1434736/


All Articles