Reputation: 271
I'm stuck with this problem:
<body onload="document.body.innerHTML="<script>alert('hi')</script>"">
The problem is that i cant use quotes within quotes within quotes. Any ideas?
Upvotes: 22
Views: 49068
Reputation: 2915
You could use a combination of backticks(`), single quotes, and double quotes.
Code:
<body onload="document.body.innerHTML=`<script>alert('hi')</script>`">
Upvotes: 2
Reputation: 4032
<body onload='document.body.innerHTML="<script>alert(\"hi\")</script>"'>
or
<body onload="document.body.innerHTML='<script>alert(\'hi\')</script>'">
It does work, but the script doesn't get executed because it is added after the browser parsed your code.
Note that if you wanted quotes within quotes within quotes within quotes you would have done: <body onload="document.body.innerHTML='<script>alert(\'\\\'hi\\\'\')</script>'" >
What is really impossible (i think) without "
is putting "
and '
in the alert.
Upvotes: 10
Reputation: 7960
Gah! First off, don't do it that way. :D
Something like:
<body></body>
<script>
window.onload = function () {
document.body.innerHTML = "<script>alert('hi')</script>";
}
</script>
. . . would be better. Consider some JQuery solutions, as well.
Even that specific approach, I wouldn't recommend, but I suspect that you are simply testing out how to add content to the body of your HTML after the page is loaded, rather than actually wanting to use the alert()
. ;) If that's the case, try something like this:
<body></body>
<script>
window.onload = function () {
document.body.innerHTML = "some text";
alert('hi'); // if you really want to test that the JS is working after load.
}
</script>
Upvotes: 0
Reputation: 944530
To represent a "
character inside an HTML attribute delimited by "
characters, use the entity "
I'd recommend attaching event listeners using JavaScript rather then using intrinsic event attributes though. It simplifies things greatly.
Note however, that browsers will not execute JavaScript added to the document with innerHTML
. If you want to add a script programatically, the use createElement
/ appendChild
et al.
Upvotes: 34