2016-08-17 2 views
1

내 서비스 작업자가 성공적으로 다음과 같은 달성 할 때 다시 제출할 때 캐시는 모두 실패 후 요청 :ServiceWorker는 - 오프라인 순간에 온라인

  • 그것은 캐시 때 오프라인 페이지를 캐시 할 때 온라인
  • 그것은 단지 반환 모든 페이지 방문

내 응용 프로그램에는 자동으로 ajax를 통해 제출되는 서명을 사용자가 입력 할 수있는 기능이 있습니다. 오프라인 상태에서 서비스 직원에게이 게시물 요청을 캡처하려고 시도하고 온라인 상태가되면 바로 요청을 다시 제출합니다.

다음은 내 serviceworker 파일의 샘플입니다.

self.addEventListener('fetch', function(event) { 
    // Intercept all fetch requests from the parent page 
    event.respondWith(
     caches.match(event.request) 
     .then(function(response) { 
      // Immediately respond if request exists in the cache and user is offline 
      if (response && !navigator.onLine) { 
       return response; 
      } 


      // IMPORTANT: Clone the request. A request is a stream and 
      // can only be consumed once. Since we are consuming this 
      // once by cache and once by the browser for fetch, we need 
      // to clone the response 
      var fetchRequest = event.request.clone(); 

      // Make the external resource request 
      return fetch(fetchRequest).then(
       function(response) { 
       // If we do not have a valid response, immediately return the error response 
       // so that we do not put the bad response into cache 
       if (!response || response.status !== 200 || response.type !== 'basic') { 
        return response; 
       } 

       // IMPORTANT: Clone the response. A response is a stream 
       // and because we want the browser to consume the response 
       // as well as the cache consuming the response, we need 
       // to clone it so we have 2 stream. 
       var responseToCache = response.clone(); 

       // Place the request response within the cache 
       caches.open(CACHE_NAME) 
       .then(function(cache) { 
        if(event.request.method !== "POST") 
        { 
         cache.put(event.request, responseToCache); 
        } 
       }); 

       return response; 
      } 
      ); 
     }) 
    ); 
}); 

나는 이것을 통합하는 최선의 방법을 찾으려고 노력하고 있습니까? 누구라도 빛을 발산 할 수 있습니까?

+0

오프라인 요청 배열을 만들려고 했습니까? 사용자가 온라인 일 때 배열을 반복합니까? – guest271314

+0

@ guest271314 현재 URL에 저장 서명 URL이있는 모든 요청을 저장하려고합니다. 온라인에서 서비스 직원에게 이러한 요청을 다시 제출하는 방법을 잘 모르겠습니다. – Matt

+0

@ guest271314 서비스 직원 내부에서 게시물 내용을 캐싱하는 데 문제가 있습니다. event.request 객체는 POST 내용이없는 것으로 보인다. – Matt

답변

2

다음 코드를 사용하여 원하는 결과를 얻었습니다.

// Cache signature post request 
    //This retrieves all the information about the POST request including the formdata body, where the URL contains updateSignature. 
// Resubmit offline signature requests 
    //This resubmits all cached POST results and then empties the array. 

self.addEventListener('fetch', function(event) { 
    // Intercept all fetch requests from the parent page 
    event.respondWith(
     caches.match(event.request) 
     .then(function(response) { 
      // Cache signature post request 
      if (event.request.url.includes('updateSignature') && !navigator.onLine) { 
       var request = event.request; 
       var headers = {}; 
       for (var entry of request.headers.entries()) { 
        headers[entry[0]] = entry[1]; 
       } 
       var serialized = { 
        url: request.url, 
        headers: headers, 
        method: request.method, 
        mode: request.mode, 
        credentials: request.credentials, 
        cache: request.cache, 
        redirect: request.redirect, 
        referrer: request.referrer 
       }; 
       request.clone().text().then(function(body) { 
        serialized.body = body; 
        callsToCache.push(serialized); 
        console.log(callsToCache); 
       });  
      } 
      // Immediately respond if request exists in the cache and user is offline 
      if (response && !navigator.onLine) { 
       return response; 
      } 
      // Resubmit offline signature requests 
      if(navigator.onLine && callsToCache.length > 0) { 
       callsToCache.forEach(function(signatureRequest) { 
        fetch(signatureRequest.url, { 
         method: signatureRequest.method, 
         body: signatureRequest.body 
        }) 
       }); 
       callsToCache = []; 
      } 


      // IMPORTANT: Clone the request. A request is a stream and 
      // can only be consumed once. Since we are consuming this 
      // once by cache and once by the browser for fetch, we need 
      // to clone the response 
      var fetchRequest = event.request.clone(); 

      // Make the external resource request 
      return fetch(fetchRequest).then(
       function(response) { 
       // If we do not have a valid response, immediately return the error response 
       // so that we do not put the bad response into cache 
       if (!response || response.status !== 200 || response.type !== 'basic') { 
        return response; 
       } 

       // IMPORTANT: Clone the response. A response is a stream 
       // and because we want the browser to consume the response 
       // as well as the cache consuming the response, we need 
       // to clone it so we have 2 stream. 
       var responseToCache = response.clone(); 

       // Place the request response within the cache 
       caches.open(CACHE_NAME) 
       .then(function(cache) { 
        if(event.request.method !== "POST") 
        { 
         cache.put(event.request, responseToCache); 
        } 
       }); 

       return response; 
      } 
      ); 
     }) 
    ); 
});