[Video courtesy of Computerphile]
How do I Prevent it?
XSS is easy enough to prevent, however the trick is to remember to watch out for it every time you accept inputs from the user. Alternatively, you can filter the input every time you output it, but this is probably a lot harder to remember.
To prevent XSS in PHP is to convert the input with htmlspecialchars. If you are not using PHP, then you can manually use string replacement functions to manually convert
<script> elements, but the user might inject
< script > etc. In these situations, I would recommend allowing users to input markdown text instead, escape this with
htmlspecialchars, and then perform the relevant conversions to html when it comes to be rendered.
Try It Yourself
For a quick and easy way to try it for yourself safely, you can download and run my example site on github. Below is a demonstration: