This type of vulnerability is normally prevented by the server. Most do, indeed, prevent this type of malicious code placement. Others, however, don’t, or do so incompletely or incorrectly. These are referred to as having “cross-site scripting vulnerabilities”, or “XSS vulnerabilities”.
One example of such vulnerabilities is malicious instructions in a comment on a blog post. Once published, subsequent visitors to the page could be at risk of the malicious code being executed in their browsers as the comment is displayed. A properly secure server would not allow those instructions to be included, or would only include them in a way that would not work.
Typically, malicious code of this form is a very short reference to more code stored elsewhere on another server – hence the “cross site” reference. Posting a malicious comment on a vulnerable site might cause every subsequent visitor to run code from a completely different site.
Note that while I’ve used blog post comments here as an example, commenting systems on major platforms are typically robust and not vulnerable. The risks of cross-site scripting vulnerabilities can apply to any type of site or service that allows user interaction.