简体   繁体   中英

Using web workers with chrome extension

What I am trying to achieve here, is to execute a XHRHttpRequest() on a worker to speedup my extension. I am using worker_proxy.js from here . It is working totally fine except that I am unable figure out how to pass a string to this worker. Here is my code:

manifest.json

"permissions": [
    "alarms",
    "activeTab",
    "tabs",
    "webNavigation",
    "http://*/*", 
    "https://*/*",
    "cookies"
   ],

   "options_page": "options.html",

   "background": {
    "persistent": false,
    "scripts": [ "worker_proxy.js","background.js"]
  },
  "content_scripts": [
    {
      "matches": ["https://*/*","http://*/*"],
      "js": ["jquery-2.1.4.js","hmac-sha256.js","enc-base64-min.js","worker_proxy.js","content.js"]
    }
  ],
  "web_accessible_resources": [ "worker_proxy.html","worker.js"],

worker.js

var somestring=getStringFromContentJS()

var xhr=new XMLHttpRequest();
var request="GETgoogle.com"
xhr.open("GET", request, false);
xhr.send(someString);

postMessage('Result\n' + xhr.responseText);

content.js

  var az_worker = new Worker(chrome.runtime.getURL('getAzProducts.js'));
  az_worker.onmessage = function(event) {
    alert('Message from worker: ' + event.data);
  };

I am able to receive the data from worker.js but how do I send data to it, ie,

var somestring=getStringFromContentJS()

To send data to a worker, simply add the following to the top of worker.js:

self.onmessage = function(event) {
    // Do something with event.data
};

and use az_worker.postMessage(somestring); to send data to it.


But your code is unnecessarily complex. If your goal is "to speedup my extension", then you should not be using Web workers to make synchronous XHR, but use asynchronous XHR on the main thread. Web Workers are great for CPU-bound tasks, but don't provide any advantage for I/O tasks such as network requests.

See https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest for tutorials on using XMLHttpRequest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM