Posting this type of a script would make every end user a prey unintentionally enabling the attack by simply running the application, with the malevolent code appearing to be portion of the web page. Though the above code is inoffensive, a real-life hacker might of course post far more risky code.
To avert XSS attacks, developers need to apply sanitization, kind of a blend of escaping, filtering, and even validating string data. It should be done once tackling with user input and output from the server.
Whenever it is possible, browser-supplied input must be validated to ensure it just includes expected characters. As an example, phone number fields must only be allowed to contain digits. Numbers and perhaps a dash or that of parentheses characters. Here, remember that input possessing characters outside the expected set must definitely be immediately rejected. Such filters should be established to look for acceptable characters and cast-off everything else.
Client-side browser script can be quite powerful in that it has proper access to all the content returned by a website application to the browser. Such a thing can include cookies that might possibly contain sensitive data, encompassing user session ids. In fact, a general exploit of XSS attacks is to send the session ID tokens of the user to the attacker so they can easily take over the session.
To avert this, most browsers now do support the Http-Only attribute on that of cookies. Once the server sets a cookie on the specific browser. Setting the Http-Only attribute informs the browser not to permit access to the cookie from the DOM. It everts client -side script-based attacks from accessing the important and sensitive data saved in those cookies.