使用具有Chrome扩展程序的Web Worker [英] Using web workers with chrome extension

查看:251
本文介绍了使用具有Chrome扩展程序的Web Worker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在这里实现的目标是在一个worker上执行XHRHttpRequest()以加快扩展速度.我正在从此处使用worker_proxy.js.除了我无法弄清楚如何将字符串传递给此工作人员之外,它的工作情况完全正常. 这是我的代码:

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);
  };

我能够从worker.js接收数据,但是如何向其发送数据, 即

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

var somestring=getStringFromContentJS()

推荐答案

要将数据发送到工作程序,只需将以下内容添加到worker.js顶部:

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
};

,然后使用az_worker.postMessage(somestring);向其发送数据.

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

但是您的代码不必要地复杂.如果您的目标是加快扩展速度",那么您应该不要使用Web Worker来制作同步XHR,而应在主线程上使用 asynchronous XHR . Web Workers非常适合与CPU绑定的任务,但对网络请求等I/O任务没有任何优势.

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.

请参见 https://developer.mozilla.org/zh-CN/docs /AJAX/Getting_Started https://developer. mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest 有关使用XMLHttpRequest的教程.

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.

这篇关于使用具有Chrome扩展程序的Web Worker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆