Use shim blob with importScripts to use CORS for Worker

This commit is contained in:
Derk-Jan Hartman 2014-01-11 16:35:00 +01:00
commit f779c2e8c5

View file

@ -57,7 +57,21 @@ var WorkerClient = function(topLevelNamespaces, mod, classname) {
}); });
} }
this.$worker = new Worker(workerUrl); try {
this.$worker = new Worker(workerUrl);
} catch ( e ) {
if ( e instanceof DOMException ) {
// Likely same origin problem. Use importScripts from a shim Worker
var blob = this.blobWorker(workerUrl),
URL = URL || webkitURL,
blobURL = URL.createObjectURL(blob);
this.$worker = new Worker(blobURL);
URL.revokeObjectURL(blobURL);
} else {
throw e;
}
}
this.$worker.postMessage({ this.$worker.postMessage({
init : true, init : true,
tlns: tlns, tlns: tlns,
@ -163,7 +177,24 @@ var WorkerClient = function(topLevelNamespaces, mod, classname) {
this.call("setValue", [this.$doc.getValue()]); this.call("setValue", [this.$doc.getValue()]);
} else } else
this.emit("change", {data: q}); this.emit("change", {data: q});
} };
this.blobWorker = function(workerUrl) {
var script = 'importScripts("' + workerUrl + '");',
blob;
try {
blob = new Blob(
[script],
{ 'type' : 'application/javascript' }
);
} catch (e) { // Backwards-compatibility
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder,
blobBuilder = new BlobBuilder();
blobBuilder.append(script);
blob = blobBuilder.getBlob('application/javascript');
}
return blob;
};
}).call(WorkerClient.prototype); }).call(WorkerClient.prototype);