Search code examples
javascriptgoogle-chromeweb-workerform-data

FormData in a webworker - in some browsers - is this wrong?


I have been playing with uploading inside a webworker, and found things working in Chrome. However, in Safari and Firefox, I get FormData is undefined.

I found out that this is fine and to be expected: as mentioned in https://stackoverflow.com/a/13970107/1238884 FormData is not defined / supported for webworkers and implements a polyfill. (note: updated polyfill @ https://gist.github.com/Rob--W/8b5adedd84c0d36aba64)

But why does it work in Chrome (v39)? Does it have a buggy implementation, or have they put in in there on purpose?


Solution

  • Chrome supports FormData in Web Workers since version 36.0.1935.0 (crbug.com/360546).

    It exists because the latest specification of FormData requires it to be exposed to Worker contexts. Firefox has not implemented this yet, but it is on their radar (bugzil.la/739173).

    I think that you're misreading my answer that you've linked. new FormData(<HTMLFormElement>); is not supported in the sense that the constructor that takes a <form> and initializes its fields based on the form elements is not supported, because <form> elements can obviously not be created in a Web worker. But you can create an empty FormData object and use it as you wish (if the browser implements the latest version of the specification).

    If you want to use the FormData API in all current browsers, then you have to load my polyfill that you referenced in your question. This polyfill returns early if it detects that the FormData API is already defined, so it won't cause issues in browsers that already support FormData. Note that this polyfill is inefficient compared to a native FormData API, because the polyfill has to create the full string upfront (in memory), whereas a native implementation can just hold light data structures for a file, and stream the file from the disk when the File/Blob is uploaded.

    For small pieces of data, this is a non-issue, but if you plan on uploading huge files, then you'd better pass the data to the main thread using postMessage (with transferables if you use typed arrays) and construct the XMLHttpRequest object over there, and send it. Web Workers are mainly useful for offloading CPU-heavy tasks, but XMLHttpRequest is mainly network (which happens on a separate IO thread, at least in Chrome), so there is no benefit of usign Web Workers over the main thread in this regard.