Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not executed when go back to previous page, behaves differently between local and live on githubpage, edge and chrome

Please check out this GithubPage where I try to recreate an issue I had.

When you click the first button, it will create a paragraph, append it to a localstorage item and display it.

When you click the second button, it will first clear the localstorage, then redirect to another page.

Now if you click the browser back button from page2, you go back to index.html, but the paragraphs are still there. If you check the localstorage, the paragraphs are deleted, as they should, but they still display as if the js script didn’t execute when coming back to the index.html.

I have this problem with chrome and Firefox, but edge behaves as I expected(coming back to index.html, no paragraphs displayed). Everything was also working as expected when I test it on local live server even with chrome. But not right on a GitHub page. Does Js script run again when visiting a page through browser’s back button? I thought so, but can someone explain what’s going on here? Thanks.

Here is the script

const addPEle = document.querySelector(".addP");
const clearPEle = document.querySelector(".clearP");
const contentEle = document.querySelector(".content");

addPEle.addEventListener("click", () => {
  const curContent = localStorage.getItem("content") || "";
  localStorage.setItem("content", `${curContent}<p>This is a paragraph.</p>`);
  displayContent();
});

clearPEle.addEventListener("click", () => {
  localStorage.setItem("content", "");
  location.href = "page2.html";
  // displayContent();
});

function displayContent() {
  contentEle.innerHTML = "";
  const content = localStorage.getItem("content") || "There is no paragraph.";
  contentEle.innerHTML = content;
  console.log("from displayContent function");
  console.log(`content: ${content}`);
  console.log(`localStorage: ${localStorage.getItem("content")}`);
}

displayContent();
like image 569
Jay Wu Avatar asked Dec 01 '25 03:12

Jay Wu


1 Answers

That is because the Back-Forward Cache preserve your page and it's state and won't refresh your page when navigate back.

You can use the PageLifeCycle events to check if your page is navigate back and do a reload if you want. See demo https://page-lifecycle.glitch.me/ from https://github.com/GoogleChromeLabs/page-lifecycle

window.addEventListener('pageshow', (event) => {
  if (event.persisted) {
    // page was restored from the bfcach
    // Do your reload or re-render page with data
  }
});
like image 150
Rex Pan Avatar answered Dec 02 '25 18:12

Rex Pan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!