You can do that by writing a few lines of code however you'll need a better method in order to achieve a consistent result in which pressing the browser/mobile back button AND hiding modal using [x] button or clicking outside the modal work identical.
I consider the following method a better solution in that sense. it works on modern browsers (HTML5 Javascript ES6) with Bootstrap 4.0 or higher but you'd be able to adapt it for older browser support.
1- Assign a data-hash="#some-hash"
attribute to all of the modals that you want to close via browser back button.
2- the block responsible for appending hash to the url
// Add hash to the URL on open modal event
$('.modal').on('shown.bs.modal', function() {
if (typeof(this.dataset.hash) !== 'undefined') {
history.pushState(null, null, this.dataset.hash)
}
})
3- listen to hide.bs.modal
event and determine if the back button is pressed or not
// trigger browser back button when the modal is dismissed (using x button etc...)
$('.modal').on('hide.bs.modal', function(event) {
if (this.dataset.pushback !== 'true') {
event.preventDefault()
history.back()
}
this.dataset.pushback = ''
})
4- the block responsible to handle browser back button. we add the pushback
attribute as a flag to indicate back button press event.
// Close current open modal (if any) on browser back event
window.onpopstate = function() {
let open_modal = document.querySelector('.modal.show')
if (open_modal) {
open_modal.dataset.pushback = 'true';
$(open_modal).modal('hide')
}
}