summaryrefslogtreecommitdiffstats
path: root/toolkit/components/antitracking/test/browser/serviceWorker.js
blob: 71c88c721af12d2e30ddf833ef4eeb195a095e22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
let value = "";
let fetch_url = "";

self.onfetch = function (e) {
  fetch_url = e.request.url;
};

// Call clients.claim() to enable fetch event.
self.addEventListener("activate", e => {
  e.waitUntil(self.clients.claim());
});

self.addEventListener("message", async e => {
  let res = {};

  switch (e.data.type) {
    case "GetHWConcurrency":
      res.result = "OK";
      res.value = navigator.hardwareConcurrency;
      break;

    case "GetScriptValue":
      res.result = "OK";
      res.value = value;
      break;

    case "SetScriptValue":
      res.result = "OK";
      value = e.data.value;
      break;

    case "HasCache":
      // Return if the cache storage exists or not.
      try {
        res.value = await caches.has(e.data.value);
        res.result = "OK";
      } catch (e) {
        res.result = "ERROR";
      }
      break;

    case "SetCache":
      // Open a cache storage with the given name.
      try {
        let cache = await caches.open(e.data.value);
        await cache.add("empty.js");
        res.result = "OK";
      } catch (e) {
        res.result = "ERROR";
      }
      break;

    case "SetIndexedDB":
      await new Promise(resolve => {
        let idxDB = indexedDB.open("test", 1);

        idxDB.onupgradeneeded = evt => {
          let db = evt.target.result;
          db.createObjectStore("foobar", { keyPath: "id" });
        };

        idxDB.onsuccess = evt => {
          let db = evt.target.result;
          db
            .transaction("foobar", "readwrite")
            .objectStore("foobar")
            .put({ id: 1, value: e.data.value }).onsuccess = _ => {
            resolve();
          };
        };
      });
      res.result = "OK";
      break;

    case "GetIndexedDB":
      res.value = await new Promise(resolve => {
        let idxDB = indexedDB.open("test", 1);

        idxDB.onsuccess = evt => {
          let db = evt.target.result;
          db.transaction("foobar").objectStore("foobar").get(1).onsuccess =
            ee => {
              resolve(
                ee.target.result === undefined ? "" : ee.target.result.value
              );
            };
        };
      });
      res.result = "OK";
      break;

    case "GetFetchURL":
      res.value = fetch_url;
      fetch_url = "";
      res.result = "OK";
      break;

    default:
      res.result = "ERROR";
  }

  e.source.postMessage(res);
});