0

I'm trying to set a URL on the browser back button. I've looked at a few examples and found this code and it works. The problem is when I click on an anchor button it does the same as when I click on the browser back button.. this is not good. I believe the problem is with this line of code - I could be wrong -

window.addEventListener('popstate', function(event){ ... })

Here's the code -

history.pushState(null, null, '<?php echo $_SERVER["REQUEST_URI"]; ?>');
window.addEventListener('popstate', function(event) {
        window.location.assign("http://newurl.com");
});

I've been working on this all day and cannot find a solution. Can someone help?

StudioTime
  • 22,603
  • 38
  • 120
  • 207
user5319102
  • 255
  • 4
  • 11

1 Answers1

2

This answer is already given, but I will try to explain what I understand using pushState.

Consider your url is "google.com/gmail"

  1. Make currentURL as temp URL, so your browser will show this URL. At this step, there will be one URL in the stack i.e google.com/gmail#!/tempURL.

    history.replaceState(null, document.title, location.pathname+"#!/tempURL");

  2. Push the previousURL as new state so now your browser will show previousURL i.e google.com/gmail.

    history.pushState(null, document.title, location.pathname);

    Current state of the stack:

    1. First element : google.com/gmail
    2. Last element : google.com/gmail#!/tempURL
  3. Now add listener to listen event

    window.addEventListener("popstate", function() {
        if(location.hash === "#!/tempURL") {
            history.replaceState(null, document.title, location.pathname);
            //replaces first element of last element of stack with google.com/gmail so can be used further
            setTimeout(function(){
                location.replace("http://www.yahoo.com/");
            },0);
        }
    }, false);
    

How to change url and detect the back button

Community
  • 1
  • 1
Farshid
  • 497
  • 1
  • 6
  • 20
  • Can someone look at the code I posted that WORKS. Then tell me why anchors buttons when clicked redirect to the back button url? – user5319102 Mar 17 '16 at 22:39