Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Service Workers respond to synchronous XHR requests?

I would like to use Service Workers to enhance an existing web site. In particular, I would like to add better offline support by having Service Workers respond to requests with placeholder resources when the actual resources are not available. This approach had been working, but I've encountered an obstacle. There are a few places in the site where synchronous XHR requests are used to load certain resources, and my Service Worker doesn't receive events for them in Chrome. (Please don't suggest eliminating synchronous XHR requests. That's desired, but out-of-scope.)

Is it supposed to be possible for a Service Worker to respond to synchronous XHR requests? I could imagine this being complicated to implement, and would understand if it wasn't supported. A "correct" answer should exist between the W3C Service Workers Specification (Working Draft) and the WHATWG Fetch Specification (Living Standard), but I haven't finished deciphering them. I would appreciate an explanation of how the specifications describe whether or not this should be supported, and/or any references to discussions about specifying or implementing this behaviour.

like image 962
Jeremy Avatar asked Mar 08 '16 23:03

Jeremy


2 Answers

According to XMLHttpRequest spec, the fetch procedure for both synchronous and asynchronous requests is the same so, in theory, it should be intercepted but Synchronous XHR has been deprecated so I would not expect Chrome to fix this.

like image 128
Salva Avatar answered Nov 07 '22 23:11

Salva


In Theory

Yes, service workers should be able to respond to synchronous XHR requests. This isn't explicitly stated in the specifications, but there's no exception that would cause synchronous XHR requests to be treated differently, and the W3C Web Platform Tests (WPT) suite has a test case to verify that it's supported: wpt/service-workers/service-worker/fetch-request-xhr-sync.https.html.

In Practice

As of January 2019, service workers can respond to synchronous XHR requests in Firefox and Edge, but not in Chrome or Safari. Chrome is planning to add support soon, but we don't know if Safari ever will.

An up-to-date browser support matrix is available at WPT.fyi. You can run the WPT test case in your own browser at https://w3c-test.org/service-workers/service-worker/fetch-request-xhr-sync.https.html.

like image 9
Jeremy Avatar answered Nov 08 '22 00:11

Jeremy