简体   繁体   中英

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.

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); } 

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 (ie the part that the user can't change) is the only way to handle security.


As someone already addressed the superficial answer (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM