vue-hooks-plus
Version:
Vue hooks library
63 lines (62 loc) • 1.64 kB
JavaScript
import { ref, watchEffect, readonly } from "vue";
function getConnection() {
const nav = navigator;
if (typeof nav !== "object")
return null;
return nav.connection || nav.mozConnection || nav.webkitConnection;
}
function getConnectionProperty() {
const c = getConnection();
if (!c)
return {};
return {
rtt: c.rtt,
type: c.type,
saveData: c.saveData,
downlink: c.downlink,
downlinkMax: c.downlinkMax,
effectiveType: c.effectiveType
};
}
function useNetwork() {
const state = ref({
since: void 0,
online: navigator == null ? void 0 : navigator.onLine,
...getConnectionProperty()
});
watchEffect((onInvalidate) => {
const onOnline = () => {
state.value = {
...state.value,
online: true,
since: new Date()
};
};
const onOffline = () => {
state.value = {
...state.value,
online: false,
since: new Date()
};
};
const onConnectionChange = () => {
state.value = {
...state.value,
...getConnectionProperty()
};
};
window.addEventListener("online", onOnline);
window.addEventListener("offline", onOffline);
const connection = getConnection();
connection == null ? void 0 : connection.addEventListener("change", onConnectionChange);
onInvalidate(() => {
window.removeEventListener("online", onOnline);
window.removeEventListener("offline", onOffline);
connection == null ? void 0 : connection.removeEventListener("change", onConnectionChange);
});
});
return readonly(state);
}
export {
useNetwork as default
};