pwa.js 1.8 KB

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