Skip to content
Advertisement

Is there a way to declare in a web page that all javascript http requests must be only to same host?

I have a small site that shows ads from different ad networks. Sometimes these ad networks serve ads that contain js code that makes HTTP requests to external servers and I found that sometimes those requests violate the privacy of my users.

Is there a way to block js request to other servers? (even if I lose the potential income from that ad or get banned from the ad network)

Advertisement

Answer

A page can use a Content Security Policy (CSP), either via HTTP header on the network response or via <meta> tag within the page. CSPs are used to control what external origins a page can communicate with.

A CSP can have many different directives which control different kinds of external requests. You sound particularly interested in the connect-src directive, which limits what origins scripts can reach via fetch (and similar APIs).

Note that scripts can still initiate external requests by adding external resources to the page, e.g., <img>, <object>, <link>, etc. If you want to limit all external requests, you can use default-src 'self' to have all directives default to only the same origin as the page itself. You can then add additional specific directives that are more permissive, if needed.

For instance, this policy blocks all foreign-origin requests and resources, except allowing frames, images, and scripts from ads.example.com (and the original origin, too):

default-src 'self'; img-src 'self' https://ads.example.com; script-src 'self' https://ads.example.com; frame-src 'self' https://ads.example.com

Since connect-src is not specified, it is limited by default-src and will not allow script communication to foreign origins.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement