2016-06-07 1 views

답변

5

서비스 근로자가 activated state 인 경우 축하 메시지 'Content is cached for offline use'을 표시하는 가장 좋은시기입니다. 서비스 직원을 등록하는 동안 아래 코드를 시도하십시오.

if ('serviceWorker' in navigator) { 
    navigator.serviceWorker.register('/service-worker.js').then(function(reg) { 
    // updatefound is fired if service-worker.js changes. 
    reg.onupdatefound = function() { 
     var installingWorker = reg.installing; 

     installingWorker.onstatechange = function() { 
     switch (installingWorker.state) { 
      case 'installed': 
      if (navigator.serviceWorker.controller) { 
       // At this point, the old content will have been purged and the fresh content will 
       // have been added to the cache. 
       // It's the perfect time to display a "New content is available; please refresh." 
       // message in the page's interface. 
       console.log('New or updated content is available.'); 
      } else { 
       // At this point, everything has been precached. 
       // It's the perfect time to display a "Content is cached for offline use." message. 
       console.log('Content is now available offline!'); 
      } 
      break; 

      case 'redundant': 
      console.error('The installing service worker became redundant.'); 
      break; 
     } 
     }; 
    }; 
    }).catch(function(e) { 
    console.error('Error during service worker registration:', e); 
    }); 
} 
+0

토스트를 표시하는 데 문제가 있습니다. 서비스 근로자가 할 수없는 DOM에 액세스해야합니다. 'console.log()'는 충분하지 않습니다. –

+0

SW에서 DOM에 액세스하지 않습니다. 서비스 근로자를 등록하는 동안이 코드를 작성해야합니다. 서비스 담당자가 활성화되면이 주소로 dom에 액세스 할 수 있습니다. –

+0

알겠습니다. 서비스 노동자를 등록하는 동안 그것을해야했습니다. 나는 SW에서 그렇게하려고 노력했다. 감사. –

1

@Prototype Chainanswer above을 테스트 한 후, 나는 이벤트 핸들러 내 취향보기 위하여, 희망 쉽게 이상/다른 사람에 대한 이해 코드를보다 쾌적한로서 anonymous functions을 중첩 반대로 named functions를 사용하고 싶었다.

그러나 문서를 정렬하는 데 소비 한 후에 만 ​​올바른 개체에서 올바른 이벤트를 수신 할 수있었습니다. 그래서 지루한 과정에서 다른 사람을 구하기 위해이 작업 예를 여기에서 공유하십시오.

관련 문제