ProgramLover
ProgramLover

Reputation: 91

checking if user input includes a <script> tag with javascript. Unexpected token {

<!DOCTYPE html>
<html>
<head>
    <script>
        function XSSPrevent(){
            var usercomments = document.getElementById('usertext').value;
            if(usercomments.contains("<script>"){
                alert("Failed");
            } else
            alert("Thank you for your comments" + usercomments);
        }
    </script>
</head>
<body>
    <form>
        <input type="text" id="usertext" maxlength=50/>
        <input type="submit" value="Enter" onclick="XSSPrevent()"/>
    </form>
</body>

It is my first time to work with both HTML form and javascript. Console

shows an unexpected token { after if loop. What's wrong?
I know it is not a good idea to use an alert method in this situation but I

just wanna check my function quickly.

Upvotes: 2

Views: 4917

Answers (2)

Julix
Julix

Reputation: 627

TL;DR: Front-end code is only for making things pretty/user-friendly and for making the experience better for people who use it as intended. Backend (i.e. the part that the user can't change) is the only way to handle security.


As someone already addressed the superficial answer (i.e. how to fix your existing question to not throw errors) the more important thing in my mind is hammering home why, or rather why not to do it.

JavaScript is front-end, which means it can be disabled and even modified! They can just take out that line of your code and proceed unhindered.

Come up with a back-end solution instead. If you're processing the form there's some kind of back-end, and they all have ways to check for and handle bad inputs. Learn how, it's worth it, and mostly not that hard.

It makes sense to have a function on the front-end in addition - if you think there are any people who might expect to be allowed to insert script tags... - In that case you could have a function (with a different name to avoid confusion) that for friendly ux purposes tells them that they're not allowed to insert script tags. Though I've never seen that kind of use case.

Upvotes: 1

mehulmpt
mehulmpt

Reputation: 16587

You're missing a bracket:

function XSSPrevent(){
    var usercomments = document.getElementById('usertext').value;
    if(usercomments.contains("<script>")){ // <-- was missing ) here
        alert("Failed");
    } else
    alert("Thank you for your comments" + usercomments);
}

Upvotes: 3

Related Questions