How to close alerts when navigating away from current page with HashRouting?

Good catch! This version maintains the existing before_unload and calls it if there’s no alert showing:

# This module is designed to allow an app using hash routing to 
# prevent navigation when an alert is being shown.  Currently,
# when an Anvil alert is being shown, the user can still press
# the back button on their browser.  The Anvil app displays the
# correct previous form, but the alert remains shown.  
#
# Using the decorator provided here, the back button will not 
# move to the previous form when an alert is being shown.
# 
# If you are calling an alert from inside a repeating row 
# template, you must import this module so its versions
# of alert and confirm are used.
#
# The import of this module must happen after the import of anvil
# itself

def alert_protection(cls):
  def _before_unload(self):
    global _alert_is_on
    
    if _alert_is_on:
      return True
    
    if hasattr(cls, 'old_before_unload'):
      return self.old_before_unload()
    
  if hasattr(cls, 'before_unload'):
    setattr(cls, 'old_before_unload', getattr(cls, 'before_unload'))
    
  setattr(cls, 'before_unload', _before_unload)
  
  global _alert_is_on
  _alert_is_on = False

  return cls
  
def alert(content, **kwargs):
  import anvil
  global _alert_is_on
  
  _alert_is_on = True
  value = anvil.alert(content, **kwargs)  
  _alert_is_on = False
  return value

def confirm(content, **kwargs):
  import anvil
  global _alert_is_on
  
  _alert_is_on = True
  value = anvil.confirm(content, **kwargs)  
  _alert_is_on = False
  return value
2 Likes