Add to Home Screen on click

Sorry for the delay in this one. There was a piece of missing architecture in anvil.js that would have made this easier. That’s now shipped.

There’s a few ways you can do this and there are a handful of javascript examples out there.
Here’s an anvil solution based on this example: PWA Install Prompt - Jason Ujma-Alvis
As well as documentation from MDN

  1. Optional - use local storage to check if we’ve shown a prompt before
from anvil_extras.storage import local_storage

def get_visited():
  return local_storage.get("seen_prompt")

def set_visited():
  local_storage["seen_prompt"] = True
  1. Add an event handler for the beforeinstallprompt event
from anvil.js import window

install_event = None

def before_install(e):
  global install_event
  e.preventDefault() # stops the default prompt displaying
  if get_visited():
    # don't show the prompt if it's been show
    return
  install_event = e
  get_open_form().show_install_btn()

window.addEventListener('beforeinstallprompt', before_install);
  1. add some logic to the main form
class Form1(Form1Template):

  def show_install_btn(self):
    self.install_prompt_btn.visible = True

  def install_prompt_btn_click(self, **event_args):
    """This method is called when the button is clicked"""
    global install_event
    if install_event is None:
      # sanity check
      self.install_prompt_btn.visible = False
      return
    install_event.prompt()
    
    # install_event.userChoice is a javascript Promise and we wait for the result
    # use anvil.js.await_promise() to do this
    result = anvil.js.await_promise(install_event.userChoice)
    
    if result.get("outcome") == "accepted":
      alert("User accepted the A2HS prompt") # Add To Home Screen (A2HS)
    else:
      alert("User dismissed the A2HS prompt")
    install_event = None
    self.install_prompt_btn.visible = False
    set_visited()

Here’s an example clone link:
https://anvil.works/build#clone:53JPYV6VHWF4FLMI=ORVM4JMIEFLHV6CST4OZLQYX

3 Likes