Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, i.e.,

var somestring=getStringFromContentJS()

like image 545
Harshil Pansare Avatar asked Sep 29 '15 20:09

Harshil Pansare


1 Answers

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.

like image 60
Rob W Avatar answered Sep 24 '22 09:09

Rob W