Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline javascript with "<script>" string closes script tag by mistake

I'm inlining a large JS program, which includes a line of code like :

doc.write("<script>var app = \"" + _2d() + "\";</script>");

Unfortunately the browser (chrome) thinks the script in the string is the closing script tag, and actually takes everything after that like its HTML text.

How do I include such a string and escape it so it does not confuse the browser HTML parsing?

like image 229
Robin Rodricks Avatar asked Sep 08 '12 14:09

Robin Rodricks


People also ask

Can a script tag be self closing?

In the same way, there are some tags which cannot be self-closed. And <script> tag is one of them. Basically, the concept of self-closing tags is an XML concept. You can use them in XHTML if the document is served with an XML content-type but not if it is served as text/html.

Does script tag need closing?

That's because SCRIPT TAG is not a VOID ELEMENT. In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all!

Do script tags go after?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.

Does script go outside body?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.


2 Answers

You should always use <\/script> if you want to put </script> in a string in JS, because </script> marks the end of the tag no matter where it shows up.

like image 158
Niet the Dark Absol Avatar answered Oct 17 '22 14:10

Niet the Dark Absol


I solved it by splitting the script tag like this SO question recommends:

doc.write("<scr"+"ipt>var app = \"" + _2d() + "\";</scr"+"ipt>");
like image 3
Robin Rodricks Avatar answered Oct 17 '22 15:10

Robin Rodricks