Cross Domain Web Worker?

天涯浪子 提交于 2020-04-07 17:59:57

问题


I have https://domain1.com (domain1) and https://domain2.com (domain2).

Domain2 serves a page containing javascript with a header "Access-Control-Allow-Origin: *"

Domain1 runs some javascript code that invokes:

new Worker("//domain2.com/script.js")

Browsers throw security exceptions.

Since starting writing this question, I have got around this problem by ajaxing the script, blobbing it and running it from that, but am I missing something in the original idea?


回答1:


I also have the same problem, hope this can help you https://gist.github.com/jtyjty99999/a730a17258fca04bfca3

 function XHRWorker(url, ready, scope) {
      var oReq = new XMLHttpRequest();
      oReq.addEventListener('load', function() {
          var worker = new Worker(window.URL.createObjectURL(new Blob([this.responseText])));
          if (ready) {
              ready.call(scope, worker);
          }
      }, oReq);
      oReq.open("get", url, true);
      oReq.send();
  }

  function WorkerStart() {
      XHRWorker("http://static.xxx.com/js/worker.js", function(worker) {
          worker.postMessage("hello world");
          worker.onmessage = function(e) {
              console.log(e.data);
          }
      }, this);
  }

  WorkerStart();



回答2:


Note : The URI passed as parameter of the Worker constructor must obey the same-origin policy. There is currently disagreement among browsers vendors on what URIs are of the same-origin; ...

Quote from https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers

The HTML5 Worker is a fairly new concept and I'm not sure how same-origin exceptions apply, however, with XmlHttpRequest, it's possible to access resources on a different domain if you have control over the the server it runs on. Resources on foreign domains are accessed via preflighted requests meaning that first an OPTIONS request is sent to resource and if the response to that has the appropriate access control headers (Access-Control-Allow-Methods, Access-Control-Allow-Origin as a minimum), then the request is repeated with the original method and receives the resource in response.




回答3:


It's pretty funny, but importScripts() inside the worker does not have the same origin restriction. So I used this plain workaround:

const workerUrl = 'https://domain2.com/script.js';
const workerBlob = new Blob([
    'importScripts(' + JSON.stringify(workerUrl) + ')',
], {type: 'application/javascript'});
const blobUrl = window.URL.createObjectURL(workerBlob);
const worker = new Worker(blobUrl);

Somewhat simpler than fetching script manually.




回答4:


Do you have allow methods set?

Try adding this to your header:

Access-Control-Allow-Methods: POST, GET, OPTIONS


来源:https://stackoverflow.com/questions/20410119/cross-domain-web-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!