Back button redirect script

后端 未结 2 1429
名媛妹妹
名媛妹妹 2020-12-01 23:17

I am trying to develop a javascript code that when a user clicks on the back button of a webpage, it can be redirected to another URL.

I have found these lines of co

相关标签:
2条回答
  • 2020-12-01 23:25

    Well if you want to use the browser back button I would push each page change into the History Api

    https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history http://www.sitepoint.com/javascript-history-pushstate/

    what you would need to do is while the user navigates your page, whenever they do something that you feel should be put into their history you use

    history.pushState({}, 'Title: Google', 'http://www.google.com/');
    

    Now when the user clicks the back button the previous page will be google.com, though I'm sure you want it be a certain end point on your webpage.

    0 讨论(0)
  • 2020-12-01 23:52

    I have found the answer in case someone else is looking for it.

    Create a separate file called history-stealer.js with the following code:

    (function(window, location) {
    history.replaceState(null, document.title, location.pathname+"#!/history");
    history.pushState(null, document.title, location.pathname);
    
    window.addEventListener("popstate", function() {
      if(location.hash === "#!/history") {
        history.replaceState(null, document.title, location.pathname);
        setTimeout(function(){
          location.replace("http://www.url.com");
        },10);
      }
    }, false);
    }(window, location));
    

    and then include this code in your HTML file:

    <script src="history-stealer.js"></script>
    

    so that it calls the history-stealer.js file

    0 讨论(0)
提交回复
热议问题