This question already has an answer here:
-
Can scripts be inserted with innerHTML?
16 answers
<!DOCTYPE html>
<html>
<body>
<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "'Python\x20Auto\x20\x3Cscript\x20type\x3D\x22text\x2Fjavascript\x22\x3E\x20alert\x28\x22JavaScript\x20alert\x22\x29\x3B\x20\x3C\x2Fscript\x3E\x20'";
}
</script>
</body>
</html>
Im setting "demo" elements innerHtml to the escaped version of
Python Auto alert("JavaScript alert"); .
If you run this html and click on the "
Click me" button. You can see the result as "Python Auto". The script tag is missing. Why this is happening ? How come the script tag and the content of it is missing ?
Need to use < for <, > for >, and \" for ". Everything else should be fine to use the actual characters, see below.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "'Python Auto <script type=\"text/javascript\"> alert(\"JavaScript alert\");</script>'";
}
</script>
</body>
</html>
!!!Please see the comment below, also, please make your question a bit more clear!!!
Instead of using \x3C
you can use <
because somehow it is escaping rest of the string,
<!DOCTYPE html>
<html>
<body>
<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "'Python\x20Auto\x20<script\x20type\x3D\x22text\x2Fjavascript\x22\x3E\x20alert\x28\x22JavaScript\x20alert\x22\x29\x3B\x20\x3C\x2Fscript\x3E\x20'";
}
</script>
</body>
</html>