I just want to create a modal page that behaves the same way, either by clicking the browser back button or the close button inside the modal file using boot file 3. I found a script that does this, but there is a problem. let's say I start with google.com, go to this mod page, and then click βModal!β., then press the return button in the browser, it will close the modal mode, if I click the βBackβ button again, it will return me to google .com (all is well). But this time, if I open the modal page and close the modal, using the close button instead. But now I will need to press the back button twice to return to google.com. If I open and close the modal using the close button inside the modal form, for example 10x. I found that I have to press the back button 10 more times to return to google.com. How to solve this problem? TIA
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <p>If you press the web browser back button not the modal "close" button, the modal will close and the hash "#myModal" will be removed for the URL</p> </div> <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div> </div> </div> </div> $('#myModal').on('show.bs.modal', function (e) { window.history.pushState('forward', null, '#modal'); }); $('#myModal').on('hide.bs.modal', function (e) { //pop the forward state to go back to original state before pushing the "Modal!" button }); $(window).on('popstate', function () { $('#myModal').modal('hide'); });
jsfiddle source
source share