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
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.
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.
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.
You could create a synchronous effect by chaining asynchronous calls together. It creates indented callbacks - whereas promises would make the code easier to read - but the 2nd Ajax call won't be made until after the 1st one has returned. Note that the 3rd parameter is set to true in both calls.
// Synchronized Ajax calls using 2 nested Asynchronous calls
// Asynchronous request #1 using traditional API
const axhr = new XMLHttpRequest();
axhr.open('GET', '/__so-example__', true);
axhr.onload = event => {
console.log("A-XHR: " + axhr.responseText);
// Asynchronous request #2 using traditional API
const sxhr = new XMLHttpRequest();
sxhr.open('GET', '/__so-example__', true);
sxhr.onload = event => {
console.log("S-XHR: " + sxhr.responseText);
}
sxhr.send();
}
axhr.send();
It's just an example. I assume that promises could be chained just as easily (but vertically stacked, instead of right indented) to create a synchronous effect.