-4

I need to over ride the default action of the back button for my mobile website. If a pop up is there, I need to close it instead of going back to history. If no pop up is there, then back button behaves like normal.I'm using react.

  • 3
    This question has been asked a million times and the answer always includes. "Don't do that.". – Scott Marcus May 15 '17 at 19:21
  • 2
    Possible duplicate of [how to stop browser back button using javascript](http://stackoverflow.com/questions/12381563/how-to-stop-browser-back-button-using-javascript) – Scott Marcus May 15 '17 at 19:22
  • 1
    You are probably looking for something like this: http://html5demos.com/history - give the popup its own point in the client browser's history. – le_m May 15 '17 at 19:24
  • 1
    These comments are perhaps a bit knee-jerk, and the duplicate is not very relevant. If I open a popup, I would certainly expect the back button to go back on an Android web browser. – Josh Lee May 15 '17 at 19:24
  • Are you talking about a real popup, or a modal window? – Thomas May 15 '17 at 20:13

1 Answers1

2

I recommend using the History API and create a new 'point' or state in the client browser's history whenever the popup pop's up:

let button = document.getElementById("button");
let popup = document.getElementById("popup");

button.addEventListener("click", event => {
  state = {}; // TODO: define useful state
  history.pushState(state, "popup");
  popup.classList.toggle("hidden");
});

window.addEventListener("popstate", event => {
  popup.classList.toggle("hidden"); // TODO: evaluate `event.state`
});
.hidden {
  display: none;
}
<button id="button">Open popup!</button>
<div id="popup" class="hidden">I am the popup. Close me by clicking your browser's 'back' button.</div>

Of course, as your application becomes more complex, you would want to use a routing library which handles this for you.

le_m
  • 19,302
  • 9
  • 64
  • 74