javascriptweb-worker

Running window.crypto.getRandomValues() from inside a Web Worker


I'm at my wit's end here. Is there any way to do this, knowing that web workers can't access the window object? Please help!


Solution

  • Edit: The original answer is now out of date

    From MDN:

    [The Web Crypto API] is available in Web Workers.

    Access it view self.crypto.getRandomValues().


    Original answer from 2012:

    There is no way to do this, seeing as the Crypto class and methods are "native code", meaning they are implemented at a lower-level in the browser, so we can't extract the code and move it somewhere else. I tried using Chrome's Transferrable Objects object gets erased from current context and passed to worker, but that throws an error. I don't think that the crypto api needs to be coupled to the DOM ( WebWorkers won't touch the DOM as it isn't thread-safe ), but I've never implemented crypto before. In Node, we have an async api, so to me, at least, it seems like it should be thread-safe.

    I created a WebWorker script to verify, that maybe, just maybe, Chrome and Firefox just had different implementations, and unfortunately, I was mistaken.

    I've sent an email to the authors of the W3C Web Crypto API Proposal, and you should as well. The draft seems to have a few open issues at this point, so it seems like it could change. Having either an async API or having the crypto API being available in Web Workers seems perfectly reasonable to me. Seems like a bad thing to have blocking the main event loop.