Let's say I have a page called Main.html that creates a web worker. If I close the Main page by changing window.location, would the web worker be terminated or would the web worker be still running?
How does Firefox or Chrome choose to "handle long-running Worker tasks after the page has closed"? If the worker's task is to send a very quick POST request, for this case, does the browser terminate the worker immediatly after the page is closed or does the browser allow the worker to finished its POST request?
Short answer: This behavior is implementation-defined, and the specification allows behavior to vary from browser to browser (or vary situationally within one browser), except for some guarantees about event queues.
Long answer:
Closing or navigating away from a page causes the browser to discard the page's document:
The W3C Worker spec says that a Worker has a "list of
Document
s". For workers spawned by a web page with awindow
(i.e., not a Worker), the list consists of the singleDocument
of the page that spawned it. The spec goes on to say:And also that:
This definition is used later:
Finally, the "closing flag" prevents new activity on the worker:
Any old, long-running activity still running may be halted by the browser, but does not have to be:
Thus, the W3C specification allows for the worker to continue running, but does not allow it to handle any further events (worker messages, timers, network communication callbacks, etc.). A particular browser may choose to kill the worker at any time for performance reasons. The way that each browser chooses to handle long-running Worker tasks after the page has closed is outside the scope of the specification; it is implementation-defined. You should not depend on this behavior one way or the other: you should tolerate immediate termination, and should also tolerate any long-running tasks not immediately terminating with the closure of the page.
Shared Workers are subject to the exact same rules, except that their list of
Document
s includes allDocuments
currently using them, so their closing flag is set only after all theDocuments
have been closed.