This is a proof-of-concept for in-browser communication using service workers, enabling synchronous
cancellation tokens and RPC calls in web workers. The service worker intercepts HTTP requests to paths like
/@cancellation@/{id}
, effectively turning it into an HTTP server accessible to the current
site. Since workers can make HTTP requests via XMLHttpRequest
, workers can communicate with the
main page synchronously, whereas the actual HTTP handler in the service worker is asynchronous and able to
call asynchronous APIs. See above for a diagram of the cancellation implementation, or the code
here.
Below is a console log of the page and a worker communicating over JSON-RPC, with the page making requests
to two addNumbers
handlers in the worker (one that's fast, one that's slow but able to be
canceled). As an added bonus, the page makes a call to a hello
handler, which the worker
implements as an RPC call back to the page itself (again, synchronously!).