Browse Source

add service worker test; disable fetch listener in chrome 58

Michael Wang 5 years ago
parent
commit
e19d7432a1
3 changed files with 236 additions and 88 deletions
  1. 118 0
      public/service-worker-test.js
  2. 103 88
      serviceWorkerAppend.js
  3. 15 0
      src/features/Login/Login.vue

+ 118 - 0
public/service-worker-test.js

@@ -0,0 +1,118 @@
+console.log("sw printing before chrome58StopHere");
+var stop = true;
+(function() {
+  try {
+    Function("var a = {...{}};");
+    stop = false;
+  } catch (error) {
+    console.log(error);
+  }
+})();
+console.log("sw printing after chrome58StopHere");
+
+// chrome 58 这个会报错,所以不执行
+if (!stop) {
+  self.addEventListener("fetch", event => {
+    // Prevent the default, and handle the request ourselves.
+    event.respondWith(
+      (async function() {
+        // console.log("fetch intercepted");
+        // Try to get the response from a cache.
+        const cachedResponse = await caches.match(event.request);
+        // Return it if we found one.
+        if (cachedResponse) {
+          console.log("cache res", event.request.url);
+          return cachedResponse;
+        }
+
+        if (
+          event.request.url.startsWith(
+            "https://ecs-test-static.qmth.com.cn/comm-ques-bank/dev/audio"
+          ) ||
+          event.request.url.startsWith(
+            "https://ecs-static.qmth.com.cn/comm-ques-bank/prod/audio/"
+          )
+        ) {
+          console.log("fetch audio intercept, try to load all");
+          const res = await fetch(event.request.url);
+
+          const reader = res.body.getReader();
+
+          // Step 2: get total length
+          const contentLength = +res.headers.get("Content-Length");
+          // console.log("content-length", contentLength);
+          // self.sessionStorage.setItem("test-sw", "1");
+          // self.postMessage({
+          //   url: event.request.url,
+          //   progress: 1,
+          // });
+
+          // self.addEventListener('message', function(event){
+          //   console.log("SW Received Message: " + event.data);
+          // console.log(event);
+          // event.ports[0].postMessage("SW Says 'Hello back!'");
+          // });
+
+          // Step 3: read the data
+          let receivedLength = 0; // received that many bytes at the moment
+          let chunks = []; // array of received binary chunks (comprises the body)
+          while (true) {
+            const { done, value } = await reader.read();
+
+            if (done) {
+              break;
+            }
+
+            chunks.push(value);
+            receivedLength += value.length;
+
+            console.log(`Received ${receivedLength} of ${contentLength}`);
+
+            self.clients.matchAll().then(function(clients) {
+              if (clients && clients.length) {
+                clients.forEach(function(client) {
+                  client.postMessage("got " + receivedLength / contentLength);
+                });
+              }
+            });
+          }
+
+          // Step 4: concatenate chunks into single Uint8Array
+          // let chunksAll = new Uint8Array(receivedLength); // (4.1)
+          // let position = 0;
+          // for (let chunk of chunks) {
+          //   chunksAll.set(chunk, position); // (4.2)
+          //   position += chunk.length;
+          // }
+
+          // const blob = await res.clone().blob();
+          // const blob = new Blob([chunksAll.buffer]);
+          const blob = new Blob(chunks);
+
+          caches.open("audios").then(function(cache) {
+            cache.put(
+              event.request,
+              new Response(blob, {
+                headers: {
+                  "Content-Type": "audio/mp3",
+                  "Content-Length": contentLength,
+                },
+              })
+            );
+          });
+
+          return new Response(blob, {
+            headers: { "Content-Type": "audio/mp3" },
+          });
+        }
+        // If we didn't find a match in the cache, use the network.
+        return fetch(event.request);
+      })()
+    );
+  });
+  // .catch(function(error) {
+  //   // Handles exceptions that arise from match() or fetch().
+  //   console.error("no cache:", error);
+  // });
+}
+console.log("sw printing end");

+ 103 - 88
serviceWorkerAppend.js

@@ -1,105 +1,120 @@
 /** append by ecs */
 // 以下为学生端添加内容
+console.log("sw printing before chrome58StopHere");
+var stop = true;
+(function() {
+  try {
+    Function("var a = {...{}};");
+    stop = false;
+  } catch (error) {
+    console.log(error);
+  }
+})();
+console.log("sw printing after chrome58StopHere ", stop);
 
-self.addEventListener("fetch", event => {
-  // Prevent the default, and handle the request ourselves.
-  event.respondWith(
-    (async function() {
-      // console.log("fetch intercepted");
-      // Try to get the response from a cache.
-      const cachedResponse = await caches.match(event.request);
-      // Return it if we found one.
-      if (cachedResponse) {
-        console.log("cache res", event.request.url);
-        return cachedResponse;
-      }
+// chrome 58 这个会报错,所以不执行
+if (!stop) {
+  self.addEventListener("fetch", event => {
+    // Prevent the default, and handle the request ourselves.
+    event.respondWith(
+      (async function() {
+        // console.log("fetch intercepted");
+        // Try to get the response from a cache.
+        const cachedResponse = await caches.match(event.request);
+        // Return it if we found one.
+        if (cachedResponse) {
+          console.log("cache res", event.request.url);
+          return cachedResponse;
+        }
 
-      if (
-        event.request.url.startsWith(
-          "https://ecs-test-static.qmth.com.cn/comm-ques-bank/dev/audio"
-        ) ||
-        event.request.url.startsWith(
-          "https://ecs-static.qmth.com.cn/comm-ques-bank/prod/audio/"
-        )
-      ) {
-        console.log("fetch audio intercept, try to load all");
-        const res = await fetch(event.request.url);
+        if (
+          event.request.url.startsWith(
+            "https://ecs-test-static.qmth.com.cn/comm-ques-bank/dev/audio"
+          ) ||
+          event.request.url.startsWith(
+            "https://ecs-static.qmth.com.cn/comm-ques-bank/prod/audio/"
+          )
+        ) {
+          console.log("fetch audio intercept, try to load all");
+          const res = await fetch(event.request.url);
 
-        const reader = res.body.getReader();
+          const reader = res.body.getReader();
 
-        // Step 2: get total length
-        const contentLength = +res.headers.get("Content-Length");
+          // Step 2: get total length
+          const contentLength = +res.headers.get("Content-Length");
 
-        if (contentLength === 0) {
-          return fetch(event.request);
-        }
-        // console.log("content-length", contentLength);
-        // self.sessionStorage.setItem("test-sw", "1");
-        // self.postMessage({
-        //   url: event.request.url,
-        //   progress: 1,
-        // });
+          if (contentLength === 0) {
+            return fetch(event.request);
+          }
+          // console.log("content-length", contentLength);
+          // self.sessionStorage.setItem("test-sw", "1");
+          // self.postMessage({
+          //   url: event.request.url,
+          //   progress: 1,
+          // });
 
-        // self.addEventListener('message', function(event){
-        //   console.log("SW Received Message: " + event.data);
-        // console.log(event);
-        // event.ports[0].postMessage("SW Says 'Hello back!'");
-        // });
+          // self.addEventListener('message', function(event){
+          //   console.log("SW Received Message: " + event.data);
+          // console.log(event);
+          // event.ports[0].postMessage("SW Says 'Hello back!'");
+          // });
 
-        // Step 3: read the data
-        let receivedLength = 0; // received that many bytes at the moment
-        let chunks = []; // array of received binary chunks (comprises the body)
-        while (true) {
-          const { done, value } = await reader.read();
+          // Step 3: read the data
+          let receivedLength = 0; // received that many bytes at the moment
+          let chunks = []; // array of received binary chunks (comprises the body)
+          while (true) {
+            const { done, value } = await reader.read();
 
-          if (done) {
-            break;
-          }
+            if (done) {
+              break;
+            }
 
-          chunks.push(value);
-          receivedLength += value.length;
+            chunks.push(value);
+            receivedLength += value.length;
 
-          // console.log(`Received ${receivedLength} of ${contentLength}`);
+            // console.log(`Received ${receivedLength} of ${contentLength}`);
 
-          self.clients.matchAll().then(function(clients) {
-            if (clients && clients.length) {
-              clients.forEach(function(client) {
-                client.postMessage([
-                  event.request.url,
-                  receivedLength,
-                  contentLength,
-                ]);
-              });
-            }
-          });
-        }
+            self.clients.matchAll().then(function(clients) {
+              if (clients && clients.length) {
+                clients.forEach(function(client) {
+                  client.postMessage([
+                    event.request.url,
+                    receivedLength,
+                    contentLength,
+                  ]);
+                });
+              }
+            });
+          }
 
-        // Step 4: concatenate chunks into single Uint8Array
-        // let chunksAll = new Uint8Array(receivedLength); // (4.1)
-        // let position = 0;
-        // for (let chunk of chunks) {
-        //   chunksAll.set(chunk, position); // (4.2)
-        //   position += chunk.length;
-        // }
+          // Step 4: concatenate chunks into single Uint8Array
+          // let chunksAll = new Uint8Array(receivedLength); // (4.1)
+          // let position = 0;
+          // for (let chunk of chunks) {
+          //   chunksAll.set(chunk, position); // (4.2)
+          //   position += chunk.length;
+          // }
 
-        // const blob = await res.clone().blob();
-        // const blob = new Blob([chunksAll.buffer]);
-        const blob = new Blob(chunks);
-        const responseFinal = new Response(blob, {
-          headers: {
-            "Content-Type": "audio/mp3",
-            "Content-Length": contentLength,
-          },
-        });
+          // const blob = await res.clone().blob();
+          // const blob = new Blob([chunksAll.buffer]);
+          const blob = new Blob(chunks);
+          const responseFinal = new Response(blob, {
+            headers: {
+              "Content-Type": "audio/mp3",
+              "Content-Length": contentLength,
+            },
+          });
 
-        caches.open("audios").then(function(cache) {
-          cache.put(event.request, responseFinal.clone());
-        });
+          caches.open("audios").then(function(cache) {
+            cache.put(event.request, responseFinal.clone());
+          });
 
-        return responseFinal.clone();
-      }
-      // If we didn't find a match in the cache, use the network.
-      return fetch(event.request);
-    })()
-  );
-});
+          return responseFinal.clone();
+        }
+        // If we didn't find a match in the cache, use the network.
+        return fetch(event.request);
+      })()
+    );
+  });
+}
+console.log("sw printing end");

+ 15 - 0
src/features/Login/Login.vue

@@ -171,6 +171,8 @@ export default {
     };
   },
   async mounted() {
+    // this.testServiceWorker();
+
     this.examShellStats();
     // await this.checkNewVersion();
     if (localStorage.getItem("__swReload")) {
@@ -295,6 +297,19 @@ export default {
   },
   methods: {
     ...mapMutations(["updateUser", "updateTimeDifference", "updateQECSConfig"]),
+    testServiceWorker() {
+      if ("serviceWorker" in navigator) {
+        // Register service worker
+        navigator.serviceWorker
+          .register("/service-worker-test.js")
+          .then(function(reg) {
+            console.log("Registration OK!. Scope is " + reg.scope);
+          })
+          .catch(function(err) {
+            console.error("Registration FAILED! " + err);
+          });
+      }
+    },
     async login() {
       if (this.disableLoginBtn || this.loginBtnLoading) {
         return;