Skip to content

Instantly share code, notes, and snippets.

@sterlingwes
Last active April 4, 2018 06:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sterlingwes/077b685c22ad6bdc04464db454b5f9f9 to your computer and use it in GitHub Desktop.
Save sterlingwes/077b685c22ad6bdc04464db454b5f9f9 to your computer and use it in GitHub Desktop.
Getting past cross-origin Web Worker exception

Cross-origin web worker scripts

If you're like me and wanted to serve your main app script from a CDN and still load a web worker, you may have encountered the following error:

Uncaught DOMException: Failed to construct 'Worker': Script at 'http://cdn.example.com/worker.js' cannot be accessed from origin 'http://example.com'

You can get around this fairly simply with importScripts by making the script you instantiate your worker with load the actual worker script from the CDN.

You can play with the following example by running two web servers to serve these files. ie: python -m SimpleHTTPServer 9000 and one on 9001.

Then, visit localhost:9000 in your browser (open the developer tools).

This also works with inline workers (see main-inline.js).

<!DOCTYPE html>
<html>
<body>
<script src="http://localhost:9001/main.js"></script>
<!-- <script src="http://localhost:9001/main-inline.js"></script> -->
</body>
</html>
/* global Worker, Blob, URL */
/*
* our primary application bundle on a CDN or other domain (9001)
*/
log('HI! I\'m your main application bundle being served from localhost:9001')
log('I\'m going to load a worker...')
// same origin as index.html
new Worker('http://localhost:9000/worker-loader.js')
inlineWorker()
function log (msg, obj) {
console.log('%c ' + msg, 'background-color: blue; color: white')
}
function inlineWorker () {
const blob = new Blob([
'console.info("loading a second worker, inline"); importScripts("http://localhost:9001/worker.js")'
])
new Worker(URL.createObjectURL(blob))
}
/* global Worker */
/*
* our primary application bundle on a CDN or other domain (9001)
*/
log('HI! I\'m your main application bundle being served from localhost:9001')
log('I\'m going to load a worker...')
// same origin as index.html
new Worker('http://localhost:9000/worker-loader.js')
function log (msg, obj) {
console.log('%c ' + msg, 'background-color: blue; color: white')
}
/* global importScripts */
/*
* the "constructor" worker script that loads in the
* actual worker script from our CDN / other domain
*/
console.info('worker loaded from same origin as index.html (localhost:9000), now for the actual worker script...')
importScripts('http://localhost:9001/worker.js')
/*
* the actual worker script that does the work
*/
console.log('worker starting work using scripts from localhost:9001!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment