title: When modal popup is open, prevent mobile "Back button" to quit the site, close the popup instead
body: <p>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!</p>
  
  <p><strong>How to make the mobile "Back button" close the popup instead of exiting the website?</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>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;
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>#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; }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="main"&gt;
  &lt;a href="" id="link"&gt;Click me&lt;/a&gt;&lt;br&gt;
  &lt;/div&gt;
  &lt;div id="popup"&gt;This is a popup window! Click mobile "Back button"&lt;/div&gt;
  &lt;div id="popupdarkbg"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Notes: </p>
  
  <ul>
  <li><p>I've already seen this Codepen <a href="https://codepen.io/dhavalt10/pen/rGLBzB" rel="nofollow noreferrer">How to disable browser back button using JavaScript</a>, but I'm not sure it it's cross-browser on Chrome, Firefox, Safari and on Android, iOS, etc.</p></li>
  <li><p>I've already seen answers about <code>window.onpopstate = function () { history.go(1); };</code> but I want to make sure this is the good practice to do it here, (so it's not a duplicate of them).</p></li>
  </ul>