简体   繁体   中英

Reload webpage when clicking back button from same domain

For a website when a user clicks a button it takes them to http://localhost:8080/differentpage. What I would like to happen is when they click the back button in their browser it reloads http://localhost:8080.

Using the below script I was able to get the desired result if I left the domain and went to a different website and back (ie. from http://localhost:8080 to http://google.com then click the back button to go back to http://localhost:8080):

window.addEventListener( "pageshow", function ( event ) {
        var historyTraversal = event.persisted || 
                         ( typeof window.performance != "undefined" && 
                              window.performance.navigation.type === 2 );
        if ( historyTraversal ) {
          window.location.reload();
          document.getElementById('topic').value = "";
        }
      });

But when I go from http://localhost:8080 to http://localhost:8080/differentpage then click back button back to http://localhost:8080 it does not reload the page. How can I make it so this action reloads the page?

Use window.location.href; Like this:

<html>
 <head>
  <title>Back Button</title>
 </head>
 <body>

  <button type="button" name="" id="back:>Back</button>

 </body>
</html>

let backButton = document.querySelector('back');
function goBack(e) {
  e.preventDefault();
  window.location.href = 'http://localhost:8080';
}

backButton.addEventLister('click', goBack);

I hope this will help, if I have really got your question!

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