If this code exists on a website, it would be one of two reasons:

 1. The website itself is malicious (or has been compromised by a malicious person).
 2. There is an [XSS][1] flaw on a website, and an attacker has injected that script. ([Or an external resource has been compromised][3] to the same effect.)

<sub>Disregarding any client machine/network compromises.</sub>


Other than that, this code cannot run on a website other than itself. The [Same Origin Policy][2] would prevent the code from altering (say) an Iframe to change destination links like so.

A legitimate website doing this on purpose would fall into category (1) IMO.

The only place this would be an issue would be inside an email message viewed via a web-based system when a user wishes to verify links. However, scripts should not be allowed to run inside HTML email messages. Most good providers prevent this from happening by stripping disallowed content and implementing a Content Security Policy.

> So is there any way to protect yourself against this besides changing your habits?

Use a [browser based password manager][4]. This should only allow you to fill out credentials on a URL match. If a phisher sends you elsewhere, the password manager won't give you the option to fill out the login form so the user will realise that something is amiss.

> Edit: Technically it's possible to use Flash on the phishing site
> itself and change the browser address bar with SWFAddress.setValue(),
> making it even possible to make the address bar appear as if it's on
> the right website.

This only changes the [URL's hash value][6], which is a [client interpreted only][5] section of the URL. This cannot change the domain or path in the address bar.


  [1]: https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
  [2]: http://en.wikipedia.org/wiki/Same-origin_policy
  [3]: https://security.stackexchange.com/q/81757/8340
  [4]: https://lastpass.com
  [5]: https://stackoverflow.com/q/2428256/413180
  [6]: http://en.wikipedia.org/wiki/Fragment_identifier