javascripthtmlweb-worker

DOM manipulation inside web worker


I know that workers can't manipulate the document directly, but how about the DOM API methods? Where did they go?!

For example if I make a request that receives a HTML fragment, what I'm supposed to do if need just to parse it in order to retrieve some data from a specific node?!

There's absolutely no way to work with virtual DOM on web workers?!


Solution

  • Support in browsers

    DOMParser or document.implementation are usually used to parse HTML to DOM in browsers. Neither is available in worker context.

    In Firefox, this is not possible because someone decided there will be only one DOM parser instance for all threads. See this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=677123

    In google chrome it doesn't work either.

    Workaround - external library

    That's right, since browser developers didn't realize DOM and XML parsing will be one of main uses of WebWorkers, we'll have to fall back to external library. The best bet seems to be JSDOM, but you'll need to figure out how to browserify it.


    Here's my failed attempt with DOMParser, I keep it for future experiments on this topic: https://jsfiddle.net/svaqb2wn/2/