Close pop up on back button

2020-02-08 04:42发布

I want to close pop up on click of back button for mobile. I implemented this using onhashchange:

window.onhashchange = function (event) {

};

In this case, if pop up is opened multiple times then on click of back button, it opens and closes the modal pop up. But, I want modal pop up to close on first back and navigate to prev page on next back.

I also tried using onbeforeunload, but it will show another alert to leave or stay on the page.

$(window).bind('beforeunload', function(e) {
    return false;
});

What is the best way to close the pop up on back button and redirect to prev page on next back?

10条回答
姐就是有狂的资本
2楼-- · 2020-02-08 05:27

bootply.com was down when I was testing my answer. See the inline script and comments at the bottom of the code below. The rest is just Twitter Bootstrap boilerplate so that I could easily test it locally.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>modal.html</title>
    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <p>If you press the back button now, you should return to whatever page you were on before this page.</p>
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Show me the modal!</button>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            <p>If you press the web browser's back button OR the modal's close buttons, the modal will close and the hash will return to "modal.html#modalClosed".</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

    <script type="text/javascript">
      // Immutable hash state identifiers. 
      var closedModalHashStateId = "#modalClosed";
      var openModalHashStateId = "#modalOpen";

      /* Updating the hash state creates a new entry
       * in the web browser's history. The latest entry in the web browser's
       * history is "modal.html#modalClosed". */
      window.location.hash = closedModalHashStateId;

      /* The latest entry in the web browser's history is now "modal.html#modalOpen".
       * The entry before this is "modal.html#modalClosed". */
      $('#myModal').on('show.bs.modal', function(e) {
        window.location.hash = openModalHashStateId;
      });  

      /* When the user closes the modal using the Twitter Bootstrap UI, 
       * we just return to the previous entry in the web 
       * browser's history, which is "modal.html#modalClosed". This is the same thing
       * that happens when the user clicks the web browser's back button. */
      $('#myModal').on('hide.bs.modal', function(e) {
        window.history.back();
      });      
    </script>
  </body>
</html>
查看更多
时光不老,我们不散
3楼-- · 2020-02-08 05:27
if (window.history && window.history.pushState) {
    $('#myModal').on('show.bs.modal', function (e) {
        window.history.pushState('forward', null, './#modal');
    });

    $(window).on('popstate', function () {
        $('#myModal').modal('hide');
    });
}
查看更多
家丑人穷心不美
4楼-- · 2020-02-08 05:34

This could be done easily using Apache Cordova but not sure if you are using it to show your page in webview.

function onBackKeyDown(e) {
  e.preventDefault();

}
document.addEventListener("backbutton", onBackKeyDown, false);

http://cordova.apache.org/docs/en/2.4.0/cordova_events_events.md.html#backbutton

查看更多
对你真心纯属浪费
5楼-- · 2020-02-08 05:34

This is my solution for bootstrap modals. It adds support closing with back button to all bootstrap modals. You can adapt it for your non-bootstrap popups.

//Modal Closer With Back Button Support (Uses EventDelegation, so it works for ajax loaded content too.)
(function() {
    var activeOpenedModalId     = null;
    var isHidingModalByPopState = false;
    $(document).on('show.bs.modal', '.modal', function() {
        activeOpenedModalId  = $(this).attr('id');
        window.location.hash = activeOpenedModalId;
    }).on('hide.bs.modal', '.modal', function() {
        if(!isHidingModalByPopState) {
            window.history.back();
        }
        isHidingModalByPopState = false;
        activeOpenedModalId     = null;
    });
    $(window).on('popstate', function() {
        if(activeOpenedModalId && window.location.hash !== '#'+activeOpenedModalId) {
            isHidingModalByPopState = true;
            $("#" + activeOpenedModalId).modal('hide');
        }
    });
})();
查看更多
登录 后发表回答