pwa.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. export default () => {
  2. //*** Determine whether or not the PWA has been installed. ***//
  3. // Step 1: Check local storage
  4. let pwaInstalled = localStorage.getItem("pwaInstalled") === "yes"
  5. // Step 2: Check if the display-mode is standalone. (Only permitted for PWAs.)
  6. if (!pwaInstalled && window.matchMedia("(display-mode: standalone)").matches) {
  7. localStorage.setItem("pwaInstalled", "yes")
  8. pwaInstalled = true
  9. }
  10. // Step 3: Check if the navigator is in standalone mode. (Again, only permitted for PWAs.)
  11. if (!pwaInstalled && window.navigator.standalone === true) {
  12. localStorage.setItem("pwaInstalled", "yes")
  13. pwaInstalled = true
  14. }
  15. //*** If the PWA has not been installed, show the install PWA prompt.. ***//
  16. let deferredPrompt = null
  17. window.addEventListener("beforeinstallprompt", (event) => {
  18. deferredPrompt = event
  19. // Show the install button if the prompt appeared.
  20. if (!pwaInstalled) {
  21. document.querySelector("#installPWA").style.display = "inline-flex"
  22. }
  23. })
  24. // When the app is installed, remove install prompts.
  25. window.addEventListener("appinstalled", (event) => {
  26. localStorage.setItem("pwaInstalled", "yes")
  27. pwaInstalled = true
  28. document.getElementById("installPWA").style.display = "none"
  29. })
  30. // When the app is uninstalled, add the prompts back
  31. return async () => {
  32. if (deferredPrompt) {
  33. deferredPrompt.prompt()
  34. let outcome = await deferredPrompt.userChoice
  35. if (outcome === "accepted") {
  36. console.log("Hoppscotch was installed successfully.")
  37. } else {
  38. console.log("Hoppscotch could not be installed. (Installation rejected by user.)")
  39. }
  40. deferredPrompt = null
  41. }
  42. }
  43. }