3

I have developed an application to analyse the network traffic while playing a youtube video. It uses chrome.webRequest and I calculate the traffic using onHeadersReceived event.

I want to do the same using service workers so that the application becomes browser independent. I fetch event of service worker, but it does not work.

Any suggestions how I can proceed?

1 Answer 1

3

Well, the broad idea is to listen to the fetch event, extract the information you need and allow the request to reach the network. You have a 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 as well):

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);
}
2
  • Thanks Salva, but in my case http request is going through youtube iframe and fetch event is not recognizing it. I want to track the response data for the video. is it possible through service worker? Jan 11, 2016 at 3:22
  • AFAIK, no, as the iframe is beyond the scope of the Service Worker. Maybe advances on foreign-fetch in the specification will cover this use case.
    – Salva
    Jan 11, 2016 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.