Cross Domain Web Worker?

后端 未结 4 1747
孤独总比滥情好
孤独总比滥情好 2021-02-05 10:51

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

Domain2 serves a page containing javascript with this header:

"Access-Control-         


        
相关标签:
4条回答
  • 2021-02-05 11:26

    Do you have allow methods set?

    Try adding this to your header:

    Access-Control-Allow-Methods: POST, GET, OPTIONS
    
    0 讨论(0)
  • 2021-02-05 11:30

    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.

    0 讨论(0)
  • 2021-02-05 11:42

    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.

    0 讨论(0)
  • 2021-02-05 11:43

    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();
    
    0 讨论(0)
提交回复
热议问题