Every once in a while, I'll see an HTML code snippet with:
%3Cscript
where the %3C
replaces the <
. Is this because the code was auto-generated or needs to display properly in an editor or was it coded that way explicitly for some reason and needs to keep that form on the HTML webpage? In case it is helpful here is the full beginning of the line of code I was questioning:
document.write(unescape('('%3Cscript
Wouldn't the line of code work just fine it you replaced the %3C
with a <
?
Every once in a while, I'll see an HTML code snippet with:
%3Cscript
where the %3C
replaces the <
. Is this because the code was auto-generated or needs to display properly in an editor or was it coded that way explicitly for some reason and needs to keep that form on the HTML webpage? In case it is helpful here is the full beginning of the line of code I was questioning:
document.write(unescape('('%3Cscript
Wouldn't the line of code work just fine it you replaced the %3C
with a <
?
3 Answers
Reset to default 3The unescape()
Javascript function converts the %3C
back to <
before it gets written into the document. This is apparently an attempt to avoid triggering scanners that might see the literal <script
tag in the source and misinterpret what it means.
When writing javascript in a script tag embedded in html, the sequence </script>
cannot appear anywhere in the script because it will end the script tag:
<script type="text/javascript">
var a = "<script>alert('hello world');</script>";
</script>
Is more or less treated as:
<script type="text/javascript">
var a = "<script>alert('hello world');
</script>
";
<script></script>
In the eyes of the html parser.
Like mplungjan said, this is convoluted way and one can simply <\/script>
in a javascript string literal to make it work:
<script type="text/javascript">
var a = "<script>alert('hello world');<\/script>";
</script>
This is not related to document.write
technically at all, it's just that document.write
is a mon place where you need "</script>"
in javascript string literal.
Also note that "<script>"
is indeed totally fine as is. It's just the "</script>"
that's the problem which you have cut out from the code.
As mentioned, possible attempt to fool scanners.
A more useful and important one is the
<\/script>
or '...<scr'+'ipt>'
needed to not end the current script block when document.writing a script inline