respond-with-body-accessed-response-worker.js (2833B)
1 importScripts('/common/get-host-info.sub.js'); 2 importScripts('test-helpers.sub.js'); 3 4 function getQueryParams(url) { 5 var search = (new URL(url)).search; 6 if (!search) { 7 return {}; 8 } 9 var ret = {}; 10 var params = search.substring(1).split('&'); 11 params.forEach(function(param) { 12 var element = param.split('='); 13 ret[decodeURIComponent(element[0])] = decodeURIComponent(element[1]); 14 }); 15 return ret; 16 } 17 18 function createResponse(params) { 19 if (params['type'] == 'basic') { 20 return fetch('respond-with-body-accessed-response.jsonp'); 21 } 22 if (params['type'] == 'opaque') { 23 return fetch(get_host_info()['HTTPS_REMOTE_ORIGIN'] + base_path() + 24 'respond-with-body-accessed-response.jsonp', 25 {mode: 'no-cors'}); 26 } 27 if (params['type'] == 'default') { 28 return Promise.resolve(new Response('callback(\'OK\');')); 29 } 30 31 return Promise.reject(new Error('unexpected type :' + params['type'])); 32 } 33 34 function cloneResponseIfNeeded(params, response) { 35 if (params['clone'] == '1') { 36 return response.clone(); 37 } else if (params['clone'] == '2') { 38 response.clone(); 39 return response; 40 } 41 return response; 42 } 43 44 function passThroughCacheIfNeeded(params, request, response) { 45 return new Promise(function(resolve) { 46 if (params['passThroughCache'] == 'true') { 47 var cache_name = request.url; 48 var cache; 49 self.caches.delete(cache_name) 50 .then(function() { 51 return self.caches.open(cache_name); 52 }) 53 .then(function(c) { 54 cache = c; 55 return cache.put(request, response); 56 }) 57 .then(function() { 58 return cache.match(request.url); 59 }) 60 .then(function(res) { 61 // Touch .body here to test the behavior after touching it. 62 res.body; 63 resolve(res); 64 }); 65 } else { 66 resolve(response); 67 } 68 }) 69 } 70 71 self.addEventListener('fetch', function(event) { 72 if (event.request.url.indexOf('TestRequest') == -1) { 73 return; 74 } 75 var params = getQueryParams(event.request.url); 76 event.respondWith( 77 createResponse(params) 78 .then(function(response) { 79 // Touch .body here to test the behavior after touching it. 80 response.body; 81 return cloneResponseIfNeeded(params, response); 82 }) 83 .then(function(response) { 84 // Touch .body here to test the behavior after touching it. 85 response.body; 86 return passThroughCacheIfNeeded(params, event.request, response); 87 }) 88 .then(function(response) { 89 // Touch .body here to test the behavior after touching it. 90 response.body; 91 return response; 92 })); 93 });