使用浏览器的"BACK"来触发脚本(js或jQuery).功能 [英] Triggering a script (js or jQuery) using browser's "BACK" function
问题描述
当通过浏览器的返回"按钮或键盘命令到达页面时,我找不到执行脚本的方法.(背景:我需要知道是否使用浏览器的BACK按钮或键盘命令打开了一个页面.然后,我可以检查存储的sessionStorage变量并触发一些适当的操作).
I can't find a way to execute a script when a page is reached via the browser's BACK button or key command. (Background: I need to know if a page was opened using the browser's BACK button or key command. Then I could check for a stored sessionStorage varible and trigger some appropriate stuff).
例如,如果我将其放入页面代码中
If, for example, I put this into my page code
<script>
$(document).ready(function() {
alert("YES!");
/* in the real situation: do something */
})
</script>
,当我通过链接加载页面或通过在地址栏中键入其URL直接打开页面时,将显示警报.
, the alert will be displayed when I load the page via a link or by opening it directly by typing its URL into the address bar.
但是,当我通过返回"按钮进入该页面时,该警报将不会出现.
But this alert will not appear when I come to that page via the BACK button.
我使用 $(window).on("load",function(){...
和 $(window).on("navigate",function(){...
-也没有成功...
I tried the same using $(window).on("load", function() {...
and $(window).on("navigate", function () {...
- no success either...
编辑/添加:
我刚刚意识到浏览器在这方面的行为有所不同:Chrome,Opera,IE和Firefox Windows将正确地重新加载页面(并触发 document.ready()
和 onload()
事件),但Firefox Mac和Safari不会-他们从缓存加载整个页面,而不会触发 document.ready()
或 onload()
.(我还没有尝试过移动浏览器)
I just realized that browsers behave differently in this respect: Chrome, Opera, IE and Firefox Windows will reload the page correctly (and trigger document.ready()
and onload()
events) , but Firefox Mac and Safari will not - they load the whole page from cache without triggering document.ready()
or onload()
. (I haven't tried mobile browsers yet)
所以我搜索了避免缓存内容的解决方案,但是到目前为止我发现并尝试过的内容(很多!)也没有用...
So i searched for solutions avoiding the cached content, but what I've found and tried so far (which is a lot!) hasn't worked either...
推荐答案
在阅读了很多帖子并尝试了其中的解决方案并将其范围缩小到浏览器问题之后,我发现了这个答案,这会迫使网页也重新加载到Safari(显然还有Firefox/Mac)中:
after reading lots of posts and trying the solutions in there and narrowing the thing down to a browser issue, I discovered this answer, which forces the page to be reloaded also in Safari (and apparently also Firefox/Mac):
https://stackoverflow.com/a/13123626/5641669
本质上,此jQuery代码通过Safari上的后退按钮将页面重新加载到其原始状态,这也允许在页面加载时触发任何所需的脚本:
Essentially, this jQuery code reloads the page in its original state when coming there via the back button on Safari, which also allows to trigger any desired script on pageload:
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
这篇关于使用浏览器的"BACK"来触发脚本(js或jQuery).功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!