0

I have 2 pages, when i go back from page-2 to index the content don't reload, and the functions don't work correctly.

in the index page:

window.onload = function() {
     document.querySelector('h2').innerText = Math.floor(Math.random() * 101);
 };

But when I go back from the page-2, the onload function dont work.

I know that i can use window.onpageshow for this work. But, isn't there any more automatic way to refresh the page when come back?

I tried use the meta tag <meta http-equiv="Cache-control" content="no-cache"> but don't work.

      window.onload = function(event) {
        document.querySelector('h2').innerText = Math.floor(Math.random() * 101);
       };
 
        function navigate(link) {
          window.location.href = 'page-2.html';
         
     }
      
  
      <h2></h2>
      <button onclick="navigate('page-2.html');">Page 2</button>
Camile
  • 153
  • 1
  • 8
  • 1
    Please edit your question to include a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of the shortest code necessary to replicate the issue. – Michael M. May 27 '23 at 19:39
  • Read [How do we control web page caching, across all browsers?](https://stackoverflow.com/questions/49547/how-do-we-control-web-page-caching-across-all-browsers) – Gabriele Petrioli May 27 '23 at 19:48

1 Answers1

0

Use onbeforeunload Like in this snippet. Event = beforeunload So if you add Event Listeners, this will look like this :

You don't have a link to go back to the page in the snippet, so this will be impossible to click on the back button but it will work if you try this code on your machine and if you have a page named page-2.html in the same folder!

        window.addEventListener("beforeunload",reload);
        window.addEventListener("load",init);
        let title, button;
        function reload(e){
            window.location.reload(true);
        }
        function init(event) {
            title = document.querySelector('h2');
            title.innerText = Math.floor(Math.random() * 101);
            button = document.querySelector('button');
            button.addEventListener("click",() => {navigate("page-2.html");});
        };
        function navigate(link) {
            window.location.href = link;
        }
      <h2></h2>
      <button>Page 2</button>
tatactic
  • 1,379
  • 1
  • 9
  • 18