返回上一页时,Javascript 不执行,本地和实时在 githubpage、edge 和 chrome 上的行为不同

Jay*_* Wu 2 javascript browser back local-storage github-pages

请查看这个GithubPage,我在其中尝试重新创建我遇到的问题。

\n

当您单击第一个按钮时,它将创建一个段落,将其附加到本地存储项并显示它。

\n

当您单击第二个按钮时,它将首先清除本地存储,然后重定向到另一个页面。

\n

现在,如果您从 page2 单击浏览器后退按钮,您将返回到 index.html,但段落仍然在那里。如果您检查本地存储,这些段落会被删除,因为它们应该被删除,但它们仍然显示,就像返回到 index.html 时 js 脚本没有\xe2\x80\x99t 执行一样

\n

我在使用 chrome 和 Firefox 时遇到了这个问题,但 Edge 的行为符合我的预期(回到 index.html,没有显示任何段落)。当我在本地实时服务器上测试它时,即使使用 Chrome,一切也都按预期工作。但在 GitHub 页面上并不正确。通过browser\xe2\x80\x99s后退按钮访问页面时Js脚本是否再次运行?我是这么认为的,但是有人可以解释一下这里发生了什么\xe2\x80\x99s吗?谢谢。

\n

这是脚本

\n
const addPEle = document.querySelector(".addP");\nconst clearPEle = document.querySelector(".clearP");\nconst contentEle = document.querySelector(".content");\n\naddPEle.addEventListener("click", () => {\n  const curContent = localStorage.getItem("content") || "";\n  localStorage.setItem("content", `${curContent}<p>This is a paragraph.</p>`);\n  displayContent();\n});\n\nclearPEle.addEventListener("click", () => {\n  localStorage.setItem("content", "");\n  location.href = "page2.html";\n  // displayContent();\n});\n\nfunction displayContent() {\n  contentEle.innerHTML = "";\n  const content = localStorage.getItem("content") || "There is no paragraph.";\n  contentEle.innerHTML = content;\n  console.log("from displayContent function");\n  console.log(`content: ${content}`);\n  console.log(`localStorage: ${localStorage.getItem("content")}`);\n}\n\ndisplayContent();\n
Run Code Online (Sandbox Code Playgroud)\n

Rex*_*Pan 5

这是因为后退缓存会保留您的页面及其状态,并且在向后导航时不会刷新您的页面。

您可以使用 PageLifeCycle 事件来检查您的页面是否导航回来,并根据需要重新加载。请参阅https://github.com/GoogleChromeLabs/page-lifecycle中的演示https://page-lifecycle.glitch.me/

window.addEventListener('pageshow', (event) => {
  if (event.persisted) {
    // page was restored from the bfcach
    // Do your reload or re-render page with data
  }
});
Run Code Online (Sandbox Code Playgroud)