flimmerkiste
flimmerkiste

Reputation: 271

HTML:Use quotes within quotes within quotes

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

Answers (4)

KetZoomer
KetZoomer

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

Alexandre Khoury
Alexandre Khoury

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 &quot; is putting " and ' in the alert.

Upvotes: 10

talemyn
talemyn

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

Quentin
Quentin

Reputation: 944530

To represent a " character inside an HTML attribute delimited by " characters, use the entity &quot;

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

Related Questions