GoogleChrome / samples

A repo containing samples tied to new functionality in each release of Google Chrome.
https://www.chromestatus.com/samples
Apache License 2.0
5.77k stars 2.38k forks source link

Basic service worker demo misleadingly suggests that cross-origin requests can be intercepted #761

Closed Tomaz-Vieira closed 2 years ago

Tomaz-Vieira commented 2 years ago

The Basic Demo in the service worker samples page performs different actions on the requests depending on the location, stating in a comment: "// Skip cross-origin requests, like those for Google Analytics."

As far as I understand, Service Workers can't intercept cross-domain requests, so this might mislead others (as it did me) into thinking that this would be possible.

jeffposnick commented 2 years ago

It's definitely possible for a service worker's fetch event handler to respond to a cross-origin request.

A service worker can only control a same-origin web page that's under it's scope. If that web page makes a request for a cross-origin resource, via a fetch('https://cross-origin.example.com') or some other loading mechanism, like <script src="https://cross-origin.example.com">, the fetch event handler will be fired and the service worker can respond.