UNPKG

offline-detector

Version:

A lightweight TypeScript library for detecting online/offline status in browsers with modern bundler support. Minimal dependencies, tree-shakable, and works with any bundler.

3 lines (2 loc) 2.21 kB
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).OfflineDetector={})}(this,function(e){"use strict";function n(e){const{interval:n,callback:t}=e;let o=null;return{start(){o||(o=setInterval(t,n))},stop(){o&&(clearInterval(o),o=null)}}}e.createOfflineDetector=function(e={}){const{onOnline:t,onOffline:o,stateChangeDebounceDelay:i=1e3,networkVerification:r={},nativeEvents:a={}}=e,{enabled:l=!0,url:s="https://www.google.com/favicon.ico",requestTimeout:c=5e3,interval:f=6e4,maxFailures:u=3}=r,{enabled:d=!0}=a;let m=!1,w=!0,v=0;if(!("undefined"!=typeof window&&"undefined"!=typeof navigator))throw new Error("OfflineDetector can only be used in browser environments");const p=function(e){const{delay:n,callback:t}=e;let o=null;return{call(){o&&clearTimeout(o),o=setTimeout(t,n)},cancel(){o&&(clearTimeout(o),o=null)}}}({delay:i,callback:()=>{w?t?.():o?.()}}),y=e=>{if(w===e)return;const n=w;w=e,l&&m&&(e&&!n?(g.stop(),O.start()):!e&&n&&(O.stop(),g.start())),p.call()},h=async()=>{if(!l)return navigator.onLine;try{const e=await async function(e){const{testUrl:n,timeout:t}=e;try{const e=new Promise((e,n)=>{setTimeout(()=>n(new Error("Timeout")),t)}),o=fetch(n,{method:"HEAD",mode:"no-cors",cache:"no-cache"});return await Promise.race([o,e]),!0}catch{return!1}}({testUrl:s,timeout:c});return e}catch{return!1}},b=async()=>{if(!m)return;await h()?(v=0,w||y(!0)):w&&(v++,v>=u&&y(!1))},L=function(e){const{onOnline:n,onOffline:t}=e,o=()=>{n()},i=()=>{t()};return{addListeners(){window.addEventListener("online",o),window.addEventListener("offline",i)},removeListeners(){window.removeEventListener("online",o),window.removeEventListener("offline",i)}}}({onOnline:()=>{d&&(l?h().then(e=>{e&&(v=0,y(!0))}):(v=0,y(!0)))},onOffline:()=>{d&&y(!1)}}),O=n({interval:f,callback:b}),g=n({interval:Math.min(f/4,15e3),callback:b});return{start(){m||(m=!0,w=navigator.onLine,d&&L.addListeners(),l&&(w?O.start():g.start(),b()))},stop(){m&&(m=!1,d&&L.removeListeners(),O.stop(),g.stop(),p.cancel())},isOnline:()=>w,destroy(){this.stop()}}}}); //# sourceMappingURL=index.min.js.map