abu
abu

Reputation: 233

how to use Service Worker to cache cross domain resources if the response is 404?

w3:

6.2 Cross-Origin Resources and CORS¶
Applications tend to cache items that come from a CDN or other origin. It is possible to request many of them directly using <script>, <img>, <video> and <link> elements. It would be hugely limiting if this sort of runtime collaboration broke when offline. Similarly, it is possible to XHR many sorts of off-origin resources when appropriate CORS headers are set.

ServiceWorkers enable this by allowing Caches to fetch and cache off-origin items. Some restrictions apply, however. First, unlike same-origin resources which are managed in the Cache as Response objects with the type attribute set to "basic", the objects stored are Response objects with the type attribute set to "opaque". Responses typed "opaque" provide a much less expressive API than Responses typed "basic"; the bodies and headers cannot be read or set, nor many of the other aspects of their content inspected. They can be passed to event.respondWith(r) method in the same manner as the Responses typed "basic", but cannot be meaningfully created programmatically. These limitations are necessary to preserve the security invariants of the platform. Allowing Caches to store them allows applications to avoid re-architecting in most cases.

I have set the CORS header like:

Access-Control-Allow-Origin:https://xxx.xx.x.com
Access-Control-Allow-Credentials:true

but I still get an "opaque" response and I cannot ensure the code is 200. If I cache these unsuccessful responses, it will cause some problem.

For example, a chum of network causes a 404 to the cross domain resources, and I cache it, then I will always use this 404 cache response even thongth when the network problem is corrected. The same-origin resource do not have this problem.

Upvotes: 10

Views: 14222

Answers (2)

Jeff Posnick
Jeff Posnick

Reputation: 56144

The mode of a Request (allegedly) defaults to "no-cors". (I say "allegedly" because I believe I've seen situations in which an implicitly created Request used in fetch() results in a CORS-enabled Response.)

So you should be explicit about opting in to CORS if you know that your server supports it:

var corsRequest = new Request(url, {mode: 'cors'});
fetch(corsRequest).then(response => ...); // response won't be opaque.

Given a properly configured remote server, a CORS-enabled Request will result in a Response that has a type of "cors". Unlike an "opaque" Response, a "cors" Response will expose the underlying status, body, etc.

Upvotes: 11

Marco Castelluccio
Marco Castelluccio

Reputation: 10802

Unfortunately, there's no way to detect it.

For security reasons, it's explicitly not allowed: https://github.com/whatwg/fetch/issues/14.

Upvotes: 0

Related Questions