service-worker-test.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. console.log("sw printing before chrome58StopHere");
  2. var stop = true;
  3. (function() {
  4. try {
  5. Function("var a = {...{}};");
  6. stop = false;
  7. } catch (error) {
  8. console.log(error);
  9. }
  10. })();
  11. console.log("sw printing after chrome58StopHere");
  12. // chrome 58 这个会报错,所以不执行
  13. if (!stop) {
  14. self.addEventListener("fetch", event => {
  15. // Prevent the default, and handle the request ourselves.
  16. event.respondWith(
  17. (async function() {
  18. // console.log("fetch intercepted");
  19. // Try to get the response from a cache.
  20. const cachedResponse = await caches.match(event.request);
  21. // Return it if we found one.
  22. if (cachedResponse) {
  23. console.log("cache res", event.request.url);
  24. return cachedResponse;
  25. }
  26. if (
  27. event.request.url.startsWith(
  28. "https://ecs-test-static.qmth.com.cn/comm-ques-bank/dev/audio"
  29. ) ||
  30. event.request.url.startsWith(
  31. "https://ecs-static.qmth.com.cn/comm-ques-bank/prod/audio/"
  32. )
  33. ) {
  34. console.log("fetch audio intercept, try to load all");
  35. const res = await fetch(event.request.url);
  36. const reader = res.body.getReader();
  37. // Step 2: get total length
  38. const contentLength = +res.headers.get("Content-Length");
  39. // console.log("content-length", contentLength);
  40. // self.sessionStorage.setItem("test-sw", "1");
  41. // self.postMessage({
  42. // url: event.request.url,
  43. // progress: 1,
  44. // });
  45. // self.addEventListener('message', function(event){
  46. // console.log("SW Received Message: " + event.data);
  47. // console.log(event);
  48. // event.ports[0].postMessage("SW Says 'Hello back!'");
  49. // });
  50. // Step 3: read the data
  51. let receivedLength = 0; // received that many bytes at the moment
  52. let chunks = []; // array of received binary chunks (comprises the body)
  53. while (true) {
  54. const { done, value } = await reader.read();
  55. if (done) {
  56. break;
  57. }
  58. chunks.push(value);
  59. receivedLength += value.length;
  60. console.log(`Received ${receivedLength} of ${contentLength}`);
  61. self.clients.matchAll().then(function(clients) {
  62. if (clients && clients.length) {
  63. clients.forEach(function(client) {
  64. client.postMessage("got " + receivedLength / contentLength);
  65. });
  66. }
  67. });
  68. }
  69. // Step 4: concatenate chunks into single Uint8Array
  70. // let chunksAll = new Uint8Array(receivedLength); // (4.1)
  71. // let position = 0;
  72. // for (let chunk of chunks) {
  73. // chunksAll.set(chunk, position); // (4.2)
  74. // position += chunk.length;
  75. // }
  76. // const blob = await res.clone().blob();
  77. // const blob = new Blob([chunksAll.buffer]);
  78. const blob = new Blob(chunks);
  79. caches.open("audios").then(function(cache) {
  80. cache.put(
  81. event.request,
  82. new Response(blob, {
  83. headers: {
  84. "Content-Type": "audio/mp3",
  85. "Content-Length": contentLength,
  86. },
  87. })
  88. );
  89. });
  90. return new Response(blob, {
  91. headers: { "Content-Type": "audio/mp3" },
  92. });
  93. }
  94. // If we didn't find a match in the cache, use the network.
  95. return fetch(event.request);
  96. })()
  97. );
  98. });
  99. // .catch(function(error) {
  100. // // Handles exceptions that arise from match() or fetch().
  101. // console.error("no cache:", error);
  102. // });
  103. }
  104. console.log("sw printing end");