Created
January 15, 2019 14:43
-
-
Save zone117x/c3e401cddb2c015d16fd767e80a081c7 to your computer and use it in GitHub Desktop.
Check for web worker Crypto API support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Checks if the global.crypto API is supported inside web workers. | |
// Uses a serialized function inside a Blob URL to run a web worker | |
// without an external file. | |
// See https://medium.com/@roman01la/run-web-worker-with-a-function-rather-than-external-file-303add905a0 | |
function checkCryptoWorkerSupport() { | |
return new Promise((resolve) => { | |
const checkFn = () => { | |
const cryptoSupported = self.crypto && self.crypto.getRandomValues | |
postMessage(!!cryptoSupported) | |
self.close() | |
} | |
const worker = new Worker(URL.createObjectURL(new Blob(['(' + checkFn + ')()']))) | |
worker.onmessage = (event) => { | |
resolve(event.data.toString() === 'true') | |
} | |
worker.onerror = (err) => { | |
err.preventDefault() | |
resolve(false) | |
} | |
}).then((result) => { | |
return result | |
}).catch((error) => { | |
console.log(`Error when checking for crypto in worker support: ${error}`) | |
return false | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment