api-client/assets/js/pwa.js

52 lines
1.7 KiB
JavaScript
Raw Normal View History

export default () => {
//*** Determine whether or not the PWA has been installed. ***//
// Step 1: Check local storage
let pwaInstalled = localStorage.getItem("pwaInstalled") === "yes"
// Step 2: Check if the display-mode is standalone. (Only permitted for PWAs.)
if (!pwaInstalled && window.matchMedia("(display-mode: standalone)").matches) {
localStorage.setItem("pwaInstalled", "yes")
2020-02-24 18:44:50 +00:00
pwaInstalled = true
}
// Step 3: Check if the navigator is in standalone mode. (Again, only permitted for PWAs.)
if (!pwaInstalled && window.navigator.standalone === true) {
localStorage.setItem("pwaInstalled", "yes")
2020-02-24 18:44:50 +00:00
pwaInstalled = true
}
//*** If the PWA has not been installed, show the install PWA prompt.. ***//
2020-02-24 18:44:50 +00:00
let deferredPrompt = null
2020-06-19 06:56:04 +00:00
window.addEventListener("beforeinstallprompt", (event) => {
2020-02-24 18:44:50 +00:00
deferredPrompt = event
// Show the install button if the prompt appeared.
if (!pwaInstalled) {
document.querySelector("#installPWA").style.display = "inline-flex"
}
2020-02-24 18:44:50 +00:00
})
// When the app is installed, remove install prompts.
2020-06-19 06:56:04 +00:00
window.addEventListener("appinstalled", (event) => {
localStorage.setItem("pwaInstalled", "yes")
2020-02-24 18:44:50 +00:00
pwaInstalled = true
document.getElementById("installPWA").style.display = "none"
2020-02-24 18:44:50 +00:00
})
// When the app is uninstalled, add the prompts back
return async () => {
if (deferredPrompt) {
2020-02-24 18:44:50 +00:00
deferredPrompt.prompt()
let outcome = await deferredPrompt.userChoice
if (outcome === "accepted") {
2020-08-13 11:20:02 +00:00
console.log("Hoppscotch was installed successfully.")
} else {
2020-08-13 11:20:02 +00:00
console.log("Hoppscotch could not be installed. (Installation rejected by user.)")
}
2020-02-24 18:44:50 +00:00
deferredPrompt = null
}
2020-02-24 18:44:50 +00:00
}
}