1

I have a background worker thread which is communicating via XMLHttpRequest to our web server and this has been working well. That said I am having problems shutting down this worker cleanly on exit of the page. From the main page I post a stop message to the Worker and it does receive it. But when the worker attempts to perform one final XMLHttpRequest to "LogOut" from the server, this request is always failing.

Are worker threads prevented from processing network requests after the onbeforeunload event is triggered for the main page? Is there some other way to do this such that I can get a clean disconnect from the server?

I have been doing this for years from the main pages without a problem, but the Worker threads seem to have some nasty restrictions unless I am doing something wrong. The same code works just fine if I post the Stop message prior to the onbeforeunload of the user exiting the page.

Main Page:

$(window).on("beforeunload", function () {
    worker.postMessage({ Action: "Stop" });
});

Worker Script:

self.addEventListener("message", function (d) {
    switch(d.data.Action) {
        case "Stop": 
            // Simple REST GET code for logout which always fails
        break;
    }
});
MikeO
  • 195
  • 1
  • 10
  • 1
    Related questions/answers from 2013 worth reading: https://stackoverflow.com/a/20105455/5217142 , https://stackoverflow.com/a/15479699/5217142 – traktor May 31 '17 at 23:23
  • So if you can't communicate back to the main app, nor with anything else, it would seem that "terminate" is identical to posting a stop from you app. – MikeO May 31 '17 at 23:36
  • Looking around, mention is made of using _synchronous_ XMLHttpRequest from the page being unloaded to get through to the server _but_ without claim it works in all circumstanes. Others may have better information or experience to add. – traktor May 31 '17 at 23:42
  • I didn't show it but my request was synchronous and it just instantly errors out indicating that it was blocked. I would have expected it to work the same as the main page does which allows this. Sadly, I could preregister some close info for the main app to send, but that's a real kludge that's hard to maintain. – MikeO May 31 '17 at 23:48

0 Answers0