Intercepting call to the back button in my AJAX application

Viewed 75748

I have an AJAX app. A user clicks a button, and the page's display changes. They click the back button, expecting to go to the original state, but instead, they go to the previous page in their browser.

How can I intercept and re-assign the back button event? I've looked into libraries like RSH (which I couldn't get to work...), and I've heard that using the hash tag somehow helps, but I can't make sense of it.

10 Answers

The back button in the browsers normally tries to go back to the previous address. there is no native device back button pressed event in browser javascript, but you can hack it with playing with location and hash to change your app state.

imagine the simple app with two views:

  • default view with a fetch button
  • result view

to implement it, follow this example code:

function goToView (viewName) {
  // before you want to change the view, you have to change window.location.hash.
  // it allows you to go back to the previous view with the back button.
  // so use this function to change your view instead of directly do the job.
  // page parameter is your key to understand what view must be load after this.

  window.location.hash = page
}

function loadView (viewName) {
    // change dom here based on viewName, for example:

    switch (viewName) {
      case 'index':
        document.getElementById('result').style.display = 'none'
        document.getElementById('index').style.display = 'block'
        break
      case 'result':
        document.getElementById('index').style.display = 'none'
        document.getElementById('result').style.display = 'block'
        break
      default:
        document.write('404')
    }
}

window.addEventListener('hashchange', (event) => {
  // oh, the hash is changed! it means we should do our job.
  const viewName = window.location.hash.replace('#', '') || 'index'

  // load that view
  loadView(viewName)
})


// load requested view at start.
if (!window.location.hash) {
  // go to default view if there is no request.
  goToView('index')
} else {
  // load requested view.
  loadView(window.location.hash.replace('#', ''))
}
Related