tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

fetch-event-async-respond-with-worker.js (2008B)


      1 // This worker attempts to call respondWith() asynchronously after the
      2 // fetch event handler finished. It reports back to the test whether
      3 // an exception was thrown.
      4 
      5 // These get reset at the start of a test case.
      6 let reportResult;
      7 
      8 // The test page sends a message to tell us that a new test case is starting.
      9 // We expect a fetch event after this.
     10 self.addEventListener('message', (event) => {
     11  // Ensure tests run mutually exclusive.
     12  if (reportResult) {
     13    event.source.postMessage('testAlreadyRunning');
     14    return;
     15  }
     16 
     17  const resultPromise = new Promise((resolve) => {
     18    reportResult = resolve;
     19    // Tell the client that everything is initialized and that it's safe to
     20    // proceed with the test without relying on the order of events (which some
     21    // browsers like Chrome may not guarantee).
     22    event.source.postMessage('messageHandlerInitialized');
     23  });
     24 
     25  // Keep the worker alive until the test case finishes, and report
     26  // back the result to the test page.
     27  event.waitUntil(resultPromise.then(result => {
     28    reportResult = null;
     29    event.source.postMessage(result);
     30  }));
     31 });
     32 
     33 // Calls respondWith() and reports back whether an exception occurred.
     34 function tryRespondWith(event) {
     35  try {
     36    event.respondWith(new Response());
     37    reportResult({didThrow: false});
     38  } catch (error) {
     39    reportResult({didThrow: true, error: error.name});
     40  }
     41 }
     42 
     43 function respondWithInTask(event) {
     44  setTimeout(() => {
     45    tryRespondWith(event);
     46  }, 0);
     47 }
     48 
     49 function respondWithInMicrotask(event) {
     50  Promise.resolve().then(() => {
     51    tryRespondWith(event);
     52  });
     53 }
     54 
     55 self.addEventListener('fetch', function(event) {
     56  const path = new URL(event.request.url).pathname;
     57  const test = path.substring(path.lastIndexOf('/') + 1);
     58 
     59  // If this is a test case, try respondWith() and report back to the test page
     60  // the result.
     61  if (test == 'respondWith-in-task') {
     62    respondWithInTask(event);
     63  } else if (test == 'respondWith-in-microtask') {
     64    respondWithInMicrotask(event);
     65  }
     66 });