Search code examples
javascriptresponsive-designmodal-dialogback-button

When modal popup is open, prevent mobile "Back button" to quit the site, close the popup instead


When a modal popup dialog is opened, even if I add a close button (usually a X on top right), some users on mobile will use their mobile "Back button" to close the popup. But instead this will quit the site!

How to make the mobile "Back button" close the popup instead of exiting the website?

document.getElementById("link").onclick = function(e) {
  e.preventDefault();
  document.getElementById("popupdarkbg").style.display = "block";
  document.getElementById("popup").style.display = "block";
    document.getElementById('popupdarkbg').onclick = function() {
      document.getElementById("popup").style.display = "none";
      document.getElementById("popupdarkbg").style.display = "none";
  };
  return false;
}
#popup { display: none; position: fixed; top: 12%; left: 15%; width: 70%; height: 70%; background-color: white; z-index: 10; }
#popupdarkbg { position: fixed; z-index: 5; left: 0; top: 0; width: 100%; height: 100%; overflow: hidden; background-color: rgba(0,0,0,.75); display: none; }
<div id="main">
<a href="" id="link">Click me</a><br>
</div>
<div id="popup">This is a popup window! Click mobile "Back button"</div>
<div id="popupdarkbg"></div>

Notes:

  • I've already seen this Codepen How to disable browser back button using JavaScript, but I'm not sure it it's cross-browser on Chrome, Firefox, Safari and on Android, iOS, etc.

  • I've already seen answers about window.onpopstate = function () { history.go(1); }; but I want to make sure this is the good practice to do it here, (so it's not a duplicate of them).


Solution

  • Here's a rough version of how I do it in my apps:

    var showModal = function() {
        // some code here to show the HTML elements...
    
        window.history.pushState('backPressed', null, null);
        window.history.pushState('dummy', null, null);
        window.addEventListener('popstate', hideModal, { once: true });
    };
    
    var hideModal = function(event) {
        if (event.state == 'backPressed') {
            // hide the HTML elements
        }
    };
    

    The reason I add two dummy states is because the popstate event also fires when the URL hash changes, e.g. when the user overwrites the hash manually in the address bar. Checking if the current history state matches backPressed lets me verify that the event was indeed triggered by the Back button.