📜 ⬆️ ⬇️

Creating a Worker from another domain

Workers are a coherent implementation of multithreading in JavaScript. At the moment, they now have a fair amount of restrictions. For acquaintance with them (both workers and restrictions) you can read this article from habrayuzer Antelle . There are also links to primary sources of information for those interested.


Today I happened to face another task. Namely: with the problem of creating a worker from a js-file from another domain, which is currently prohibited by its specification.

The story began with the creation of a small Google Chrome extension for Chess.com, which used a third-party library. Unfortunately, it turned out that this library only works as a worker.

The problem is that Chrome itself has certain restrictions on getting files from the page context. It allows the introduction of third-party javascript-code on the page, but no more. And this means that the code from the add-on can receive a worker on a page only from the domain on which it was executed. That is, in my case: Chess.com. Of course, one could expect that someday I will get access to the combat servers of Chess.com, but I would like it to work today. I had to google.
')
Fortunately, an article with html5rocks helped find a solution: creating an inline worker via Blob. Details here . In short, you can create any text string and cram it into a so-called Blob - a rock drawing model prototype of a raw external file.

For example, this is (taken from html5rocks):
var blob = new Blob([ "onmessage = function(e) { postMessage('msg from worker'); }"]); // Obtain a blob URL reference to our worker 'file'. var blobURL = window.URL.createObjectURL(blob); var worker = new Worker(blobURL); worker.onmessage = function(e) { // e.data == 'msg from worker' }; worker.postMessage(); // Start the worker. 


Here we see that a Blob object is created, which in the browser view is “as-is-a-file”, and the source text is written to it.

But if we can create from any text Blob, then you can download any text from another site, and then stuff it into Blob?

Ok, let's try:
 $.get("https://example.com/js/worker.js", {}, function (workerCode) { var blob = new Blob([workerCode], {type : 'javascript/worker'}); var worker = new Worker(window.URL.createObjectURL(blob)); } ); 


Works. That is, in fact, we can upload any external file to the page and run it as a worker, regardless of whether the files belong to one or more domains. Yeah, like that.

Finally, I note that, despite the sensational headline, in principle, this trick is not surprising. The same can be done for single-stream javascript code: load it as text and call it via eval. In this case, it remains unclear only the slow decision to support CORS in Web Workers.

Source: https://habr.com/ru/post/261817/


All Articles