用于网络流量分析的服务工作者

Service worker for web traffic analysis

我开发了一个应用程序来分析播放 YouTube 视频时的网络流量。它使用 chrome.webRequest 我使用 onHeadersReceived 事件计算流量。

我想使用 service worker 做同样的事情,这样应用程序就可以独立于浏览器了。我获取了 service worker 的事件,但它不起作用。

有什么建议可以继续吗?

嗯,大体思路就是监听fetch事件,提取你需要的信息,让请求到达网络。你也有一个working demo in the Service Worker Cookbook: https://serviceworke.rs/api-analytics.html but the relevant code is here (in the cookbook you have the annotated source):

self.onfetch = function(event) {
  event.respondWith(
    // Log the request…
    log(event.request)
    // …and then actually perform it.
    .then(fetch)
  );
};

// Post basic information of the request to a backend for historical purposes.
function log(request) {
  var returnRequest = function() {
    return request;
  };

  var data = {
    method: request.method,
    url: request.url
  };

  return fetch(LOG_ENDPOINT, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { 'content-type': 'application/json' }
  })
  .then(returnRequest, returnRequest);
}