简体   繁体   中英

Changing where the back button leads to

I am developing a web app and want to make the back button in the browser more app like.

A user goes through these steps to post a message: List all messages -> read one message -> write reply -> gets back to message after reply

If the user then clicks the back button he will get back to the page were he wrote the reply. The prefered action would be to get back to the list of all the messages.

I've tried to use the HTML5 History API to remove the history of "write reply" and "read one message" after posting, but it doesn't seem to be possible to do that.

Are there any other way make it behave like I want, or should I just leave it as it is? I know you shouldn't mess with the back button, but I really think this would make it more logical.

you can try to do in this way:

After the user wrote the reply you can execute this js

// 1) push a fake state in the history
  history.pushState({ foo: "test" }, "test", "test.html");

// 2) add a listener when the user press the back button
  window.addEventListener('popstate', function(event) {
      //redirect user where you want
      window.location.href = '...';
  }, false);
  • Keep in mind that the code @point1 will change your URL in the address bar, so if you're using the URL with some fragments or other info in the query string you must deal with them.
  • For the code @point2, if you're in a single page web app, you must remove the listener once finished this operation.

However this is a possible solution but without know the environment I don't know if can suit your request. Hope this can help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM