UNPKG

v-offline

Version:

Vue 3 component and composable for detecting online and offline network status with reactive state and customizable polling.

78 lines (77 loc) • 1.93 kB
import Ping from "ping.js"; import { computed, defineComponent, h, onBeforeUnmount, ref } from "vue"; // src/components/VOffline.vue const _sfc_main = defineComponent({ name: "VOffline", props: { onlineClass: { type: String, required: false, default: "" }, offlineClass: { type: String, required: false, default: "" }, pingUrl: { type: String, required: false, default: "https://google.com" } }, emits: ["detected-condition"], setup(props, { slots, emit }) { const isOnline = ref(navigator.onLine || false); const events = ref([ "online", "offline", "load" ]); const url = ref(props.pingUrl || "https://google.com"); const wrapperClass = computed(() => { if (isOnline.value) return typeof props.onlineClass === "string" ? props.onlineClass : ""; else return typeof props.offlineClass === "string" ? props.offlineClass : ""; }); /** * Created lifecycle hook */ events.value.forEach((event) => window.addEventListener(event, check)); /** * Before unmount lifecycle hook */ onBeforeUnmount(() => { events.value.forEach((event) => window.removeEventListener(event, check)); }); /** * Pings the URL and emits an * detected online/offline event. * @returns {Promise<void>} */ async function check() { const p = new Ping(); try { if (await p.ping(url.value) || navigator.onLine) { isOnline.value = true; emit("detected-condition", isOnline.value); } } catch (error) { if (error || !navigator.onLine) { isOnline.value = false; emit("detected-condition", isOnline.value); } } } return () => h("div", { class: wrapperClass.value }, slots); } }); // src/install.ts let installed = false; const install = (app) => { if (!installed) { app.component("VOffline", _sfc_main); installed = true; } }; export { _sfc_main as VOffline, install as default }; //# sourceMappingURL=index.js.map