jackmoore / colorbox

A light-weight, customizable lightbox plugin for jQuery
http://www.jacklmoore.com/colorbox/
MIT License
4.75k stars 1.14k forks source link

Techniques for browser's back button closing modal window using History API? #901

Closed KingWebsites closed 3 years ago

KingWebsites commented 3 years ago

Hello, I have written a SPA which utilises the History API for all its navigation. This adds each page to the history stack when you navigate to it.

My modal windows do not currently use the History API. They only popup more details of the card you've clicked on via an AJAX call. I have set up no modal-specific 'hashbang' system or fragment identifier and there is no URL you could enter which would take you to that page with the modal open. So at the moment my modal windows work independently from the usual page generator.

Because of this, if a modal is open and the user hits the browser's back button it will take the user back to the previous page. What I would like ideally is for the back button to just close the modal window.

I can see two solutions but each has issues.

  1. Simplest. Detect back button click. If modal open then close it and ignore browser's attempt to go to previous URL. The problem with this is that I don't think it's possible to stop the browser doing this.

  2. Add hash to url when window opens, and add to History API. If you close the modal normally then add the page's URL to the History API, else if you clicked the Back button it would just reload the background page, without the modal. The problem with this is that the page needs to reload.

So I was wondering if there were any strategies you have used to somehow get the browser's back button to mimic a standard modal close? Is there an easy solution I just haven't though of?

Thanks in advance.

John..

jackmoore commented 3 years ago

Colorbox has a close method that you can bind to the popstate event (back navigation). I would use Colorbox's onOpen/onCleanup options or the global event hooks to do setup and teardown of subscribing to popstate:

$(document).bind('cbox_open', function(){
  window.addEventListener('popstate', $.fn.colorbox.close); 
});

$(document).bind('cbox_cleanup', function(){
  window.removeEventListener('popstate', $.fn.colorbox.close);
});
KingWebsites commented 3 years ago

Thanks, Jack. I never thought of that way. Much appreciated.