If this code exists on a website, it would be one of two reasons:
- The website itself is malicious (or has been compromised by a malicious person).
- There is an XSS flaw on a website, and an attacker has injected that script. (Or an external resource has been compromised to the same effect.)
Disregarding any client machine/network compromises.
Other than that, this code cannot run on a website other than itself. The Same Origin Policy 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. 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, which is a client interpreted onlyclient interpreted only section of the URL. This cannot change the domain or path in the address bar.