WayneXMayersX
WayneXMayersX

Reputation: 338

Injecting script in DOM

document.body.innerHTML = "An error occurred. Please try to login again.<br>";

document.body.innerHTML += 'Username: <input type="text" name="username"><br>';
document.body.innerHTML += 'Password: <input type="password" name="password"><br>';
document.body.innerHTML += "<input type='submit' value='Login' onclick='alert(document.getElementById('password').value)'>"

After running this code and then clicking the login button the Chrome JavaScript console gives back:

SyntaxError: expected expression, got '}'

How can I fix it?

Upvotes: 1

Views: 50

Answers (2)

Dekel
Dekel

Reputation: 62676

You need to change the quotes and escape them inside the javascript code:

document.body.innerHTML = "An error occurred. Please try to login again.<br>";

document.body.innerHTML += 'Username: <input type="text" name="username"><br>';
document.body.innerHTML += 'Password: <input type="password" name="password" id="password"><br>';
document.body.innerHTML += "<input type='submit' value='Login' onclick='alert(document.getElementById(\"password\").value)'>";

As for the reason "why the browser throws this specific error?", here is the question:

Because the code is wrong, the browser actually see the following code:

(function(event){alert(document.getElementById(
})

As you can see - after the document.getElementById( there is a closing {, which is what your browser is yelling at you about.

Upvotes: 3

ihpar
ihpar

Reputation: 676

Just escape quotes

document.body.innerHTML = "An error occurred. Please try to login again.<br>";

document.body.innerHTML += 'Username: <input type="text" name="username"><br>';
document.body.innerHTML += 'Password: <input type="password" name="password" id="password"><br>';
document.body.innerHTML += "<input type='submit' value='Login'  onclick='alert(document.getElementById(\"password\").value);return false;' />"

Upvotes: 1

Related Questions