返回上一页时,Javascript 不执行,本地和实时在 githubpage、edge 和 chrome 上的行为不同
请查看这个GithubPage,我在其中尝试重新创建我遇到的问题。
当您单击第一个按钮时,它将创建一个段落,将其附加到本地存储项并显示它。
当您单击第二个按钮时,它将首先清除本地存储,然后重定向到另一个页面。
现在,如果您从 page2 单击浏览器后退按钮,您将返回到 index.html,但段落仍然在那里。如果您检查本地存储,这些段落会被删除,正如它们应该的那样,但它们仍然显示就好像返回index.html时js脚本没有执行。
我在使用 chrome 和 Firefox 时遇到了这个问题,但 Edge 的行为符合我的预期(回到 index.html,没有显示任何段落)。当我在本地实时服务器上测试它时,即使使用 Chrome,一切也都按预期工作。但在 GitHub 页面上并不正确。 通过浏览器的后退按钮访问页面时,Js脚本是否会再次运行?我是这么认为的,但是有人可以解释一下这是怎么回事吗?谢谢。
这是脚本
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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为前后向缓存< /a> 保留您的页面及其状态,并且在返回时不会刷新您的页面。
您可以使用 PageLifeCycle 事件来检查您的页面是否导航回来,并根据需要重新加载。请参阅 https://page-lifecycle.glitch.me/ 来自 https://github.com/GoogleChromeLabs/page-lifecycle
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
-- 独立修复(仅在必要时执行) --
我也使用了
pageshow
但添加了更多层if
语句检查。我们也遇到过类似的情况,但这只是看起来这对于我们来说是 Firefox 中的一个问题(也许 Chrome 更新已经解决了这个问题?)并且仅适用于商店网格产品列表,因此我们检查用户是否也在这些页面上。
无论如何,在我们的例子中,因为这个问题只影响 Firefox 用户,所以我使用了
navigator.userAgent.toLowerCase().includes('firefox')
,它将返回true
或 < code>false因此,如果为 true,即是 Firefox 用户访问,我将使用
sessionStorage
存储他们当前的 URL 作为preVisitedPage
变量,并且每个新的页面访问会将currentURL
与我们存储的 var preVisitedPage 进行比较。当我开始跟踪用户浏览历史记录的方向时,出现的有趣的事情是,当这个问题确实发生时,根据控制台日志返回信息的方式,用户似乎根据控制台所说的值进行了刷新
0
用于返回历史方向(刷新),但预期控制台会给出-1
值(向后导航),即单击的值; (值+1
表示向前导航)。然后,我们引用我们的语句来检查当前页面是否与上一个会话访问的页面不同。正确的刷新是当前页面和先前会话访问的页面将是相同的 URL。如果前一个会话访问的页面返回的 URL 值与当前页面的 URL 值不同,则表明我们发现了错误,此时我们会强制重新加载,这几乎是无缝发生的。
以下是完整的 Javascript 代码:
通过提取整个函数内的一些案例,可以进一步改进这一点,使这些案例更具全局性/可重用性,从而使该函数在
createFirefoxBrowsingStoreGridDirtyFix
中包含更少的代码> 功能。-- Isolated Fix (executes only when necessary) --
I also used
pageshow
but have added more layers ofif
statement checks..We had similar situation, however this only seemed to be an issue in Firefox for us (maybe a Chrome update has resolved this?) and only for the store-grid products listings, so we check that the user is on those pages as well.
Anyway, in our case because this issue was only affecting Firefox users, I used
navigator.userAgent.toLowerCase().includes('firefox')
which will returntrue
orfalse
so if it is true, that it is a Firefox user visiting, I will then store their current URL with
sessionStorage
aspreVisitedPage
variable, and each new page visit will compare thatcurrentURL
to our stored var preVisitedPage.Funny thing that came up once I started tracking the direction a user is travelling through their browsing history is that when this issue did occur, according to how the console log was returning info, it appeared as though the user refreshed based that console says the value
0
for returning history direction (refresh), but expected was that the console would give the value of-1
(backwards navigation) which is what was clicked; (the value+1
would indicate forwards navigation).We then reference our statement that checks if the current page is different from the previous session visited page. A proper refresh would be that current page and previous session visited page would be the same URL. If the previous session visited page is returning a different value for the URL than that of the current page, that we have found our bug occurring and we force a reload at this point which happens almost seamlessly.
Here is the full Javascript code:
This could likely be further improved by extracting some of the cases inside the overall function, to make those more global/reusable, which would then make this function contain less code within the
createFirefoxBrowsingStoreGridDirtyFix
function.