Browser back button using React

后端 未结 4 1325
醉话见心
醉话见心 2020-12-16 22:27

I am using React. I want to warn the user when the user clicks on the back button.

What I had done was

handleWindowClose = (ev) => {
    ev.preventD         


        
相关标签:
4条回答
  • 2020-12-16 22:43

    EDIT

    Looks like onbeforeunload is what you want: check this related question, which contains a useful demo.

    Also the MDN docs contain a useful example.


    Assuming you've got some good reason for not wanting to use react-router, I'll sketch the javascript way of doing this

    It looks like you're capturing the wrong event. You want to grab any change of the url hash, so you should use onhashchange.

    Example from the docs:

    if ("onhashchange" in window) {
        alert("The browser supports the hashchange event!");
    }
    
    function locationHashChanged() {
        if (location.hash === "#somecoolfeature") {
            somecoolfeature();
        }
    }
    
    window.onhashchange = locationHashChanged;
    

    However, I'd give react-router a go, given that you're developing in React. In which case, browserHistory would be your friend.

    0 讨论(0)
  • 2020-12-16 22:49

    I had a similar issue and fixed that this way:

    componentDidUpdate(){
      
        window.onpopstate  = (e) => {
            // Tour code...
        }      
    }
    
    0 讨论(0)
  • 2020-12-16 22:54

    I having below problems when handling the back button in reactjs

    1. First popstate event is not being called at the first time
    2. It is called twice after executing my back button custom logic

    to Solve problem 1 I did the following code

      componentDidMount() {
        window.history.pushState(null, null, window.location.pathname);
        window.addEventListener('popstate', this.onBackButtonEvent);
      }
    

    to solve problem 2 I did below code,

       onBackButtonEvent = (e) => {
        e.preventDefault();
        if (!this.isBackButtonClicked) {
    
      if (window.confirm("Do you want to save your changes")) {
           this.isBackButtonClicked = true;
           // your custom logic to page transition,like react-router-dom history.push()
            } else {
             window.history.pushState(null, null, window.location.pathname);
             this.isBackButtonClicked = false;
           }
        }
      }
    

    don't forget to add this.isBackButtonClicked = false; in constructor and unscubscribe the events.

      componentWillUnmount = () => {
        window.removeEventListener('popstate', this.onBackButtonEvent);
      }
    
    0 讨论(0)
  • 2020-12-16 22:58

    Try this code:

    componentDidMount() {
        window.addEventListener("popstate", this.onBackButtonEvent)
    }
    
    componentWillUnmount() {
      window.removeEventListener("popstate", this.onBackButtonEvent)
    }
    
    onBackButtonEvent = () => {
        window.history.forward()
    }
    
    0 讨论(0)
提交回复
热议问题