Service Worker does not allow XMLHttpRequest

1,136 views
Skip to first unread message

Lucas Pardue

unread,
Feb 9, 2018, 1:00:00 PM2/9/18
to emscripten-discuss
Hi,

We have a little project that we've run through emscripten and it produces an asm.js output called example.js, and example.js.mem. Inside example.js is the generated function fetchRemotePackage(), which uses XMLHttpRequest (XHR is also used elsewhere in example.js).

I've tried to use this in my Service Worker, starting simply with importScripts('example.js'). Unforturnately both Chrome and Firefox return a ReferenceError stating that XMLHttpRequest is not defined. It seems that Service Worker does not support XHR and it would rather I use the WHATWG Fetch API. Note that this is seems to be completely distinct from Emscripten's Fetch API.

I wondered if this issue with Service Worker was already on Emscripten's radar, a search did not yield much. I also had a look if there was some kind of build option that would replace XHR with Fetch but did not have much luck.

I suppose I could manually transform the generated code with --js-transform but that does not seem ideal, especially since the problem is so broad as to affect all Service Workers.

Any tips?

Kind regards
Lucas


Alon Zakai

unread,
Feb 12, 2018, 4:20:08 PM2/12/18
to emscripten-discuss
Interesting, I didn't know Service Workers disallowed XHRs but allow fetch. Then yes, we should use fetch where it is available.

The place to fix this is in src/shell.js, in readAsync. Apparently fetch is in all modern browsers now, https://caniuse.com/#search=fetch so we can probably just use fetch (or maybe fall back to XHR if legacy vm support is enabled).

Feel free to open a PR with that, or if not then please open a github issue for this and hopefully someone else will soon.

--
You received this message because you are subscribed to the Google Groups "emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to emscripten-discuss+unsub...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Lucas Pardue

unread,
Feb 13, 2018, 10:25:36 AM2/13/18
to emscripten-discuss
Hi Alon,

Thanks for the feedback. 

I'm not sure legacy vm support is.

Looking at the code, it seems that XHR is used in the browser environment (ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER), so replacing XHR with Fetch is possible and preferred. Feature detection could be used to detect Fetch and fallback.

I don't know if we have the resource to make a PR. I've created issue #6241 to track the problem. A PR (whomever writes it) can reference that issue.

Kind regards
Lucas
Reply all
Reply to author
Forward
0 new messages