tor-browser

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

sw.js (2272B)


      1 importScripts('sw-helpers.js');
      2 
      3 async function getFetchResult(record) {
      4  const response = await record.responseReady.catch(() => null);
      5  if (!response) return null;
      6 
      7  return {
      8    url: response.url,
      9    status: response.status,
     10    text: await response.text().catch(() => 'error'),
     11  };
     12 }
     13 
     14 function handleBackgroundFetchEvent(event) {
     15  let matchFunction = null;
     16 
     17  switch (event.registration.id) {
     18    case 'matchexistingrequest':
     19      matchFunction = event.registration.match.bind(
     20          event.registration, '/background-fetch/resources/feature-name.txt');
     21      break;
     22    case 'matchexistingrequesttwice':
     23      matchFunction = (async () => {
     24        const match1 = await event.registration.match('/background-fetch/resources/feature-name.txt');
     25        const match2 = await event.registration.match('/background-fetch/resources/feature-name.txt');
     26        return [match1, match2];
     27    }).bind(event.registration);
     28      break;
     29    case 'matchmissingrequest':
     30      matchFunction = event.registration.match.bind(
     31          event.registration, '/background-fetch/resources/missing.txt');
     32      break;
     33    default:
     34      matchFunction = event.registration.matchAll.bind(event.registration);
     35      break;
     36  }
     37 
     38  event.waitUntil(
     39    matchFunction()
     40      // Format `match(All)?` function results.
     41      .then(records => {
     42        if (!records) return [];  // Nothing was matched.
     43        if (!records.map) return [records];  // One entry was returned.
     44        return records;  // Already in a list.
     45      })
     46      // Extract responses.
     47      .then(records =>
     48        Promise.all(records.map(record => getFetchResult(record))))
     49      // Clone registration and send message.
     50      .then(results => {
     51        const registrationCopy = cloneRegistration(event.registration);
     52        sendMessageToDocument(
     53          { type: event.type, eventRegistration: registrationCopy, results })
     54      })
     55      .catch(error => {
     56        sendMessageToDocument(
     57          { type: event.type, eventRegistration:{}, results:[], error:true })
     58      }));
     59 }
     60 
     61 self.addEventListener('backgroundfetchsuccess', handleBackgroundFetchEvent);
     62 self.addEventListener('backgroundfetchfail', handleBackgroundFetchEvent);
     63 self.addEventListener('backgroundfetchabort', handleBackgroundFetchEvent);