Making it easier to install Discourse as a PWA

I have simply added the button by creating a theme component.

Just create new theme component…

add following js code let say in header

<script>
    let deferredPrompt; // Allows to show the install prompt
const installButton = document.getElementById("install_button");

window.addEventListener("beforeinstallprompt", e => {
  console.log("beforeinstallprompt fired");
  // Prevent Chrome 76 and earlier from automatically showing a prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  // Show the install button
  installButton.hidden = false;
  installButton.addEventListener("click", installApp);
});
function installApp() {
  // Show the prompt
  deferredPrompt.prompt();
  installButton.disabled = true;

  // Wait for the user to respond to the prompt
  deferredPrompt.userChoice.then(choiceResult => {
    if (choiceResult.outcome === "accepted") {
      console.log("PWA setup accepted");
      installButton.hidden = true;
    } else {
      console.log("PWA setup rejected");
    }
    installButton.disabled = false;
    deferredPrompt = null;
  });
}
window.addEventListener("appinstalled", evt => {
  console.log("appinstalled fired", evt);
});
</script>

And place the following html wherever you require the install button

<button id="install_button" hidden>Install</button>

it is hidden by default and will appear if PWA is not installed.

I have tested it for chrome.

6 Likes