在 Javascript 中检测浏览器刷新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3247743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:52:02  来源:igfitidea点击:

Detect Browser Refresh in Javascript

javascriptjquery

提问by Nick

I am curious if there is a way to detect the browser refresh event in javascript specifically. We are using the jQuery.address plugin to provide forward and back button functionality to AJAX functions. The problem I am facing is that this plugin does not seem to detect if the user has refreshed the page.

我很好奇是否有一种方法可以专门检测 javascript 中的浏览器刷新事件。我们正在使用 jQuery.address 插件为 AJAX 函数提供前进和后退按钮功能。我面临的问题是这个插件似乎没有检测到用户是否刷新了页面。

This code is executed each time the user moves forward or back in the browser history. I would also like it to exexute when the user refreshes.

每次用户在浏览器历史记录中向前或向后移动时,都会执行此代码。我也希望它在用户刷新时执行。

 $.address.init(function(event) {
}).change(function(event) {

        SummaryDiv.SwapPanels(newPanelID);
    }

Any ideas?

有任何想法吗?

采纳答案by LukeN

A naive attempt of mine would be to simply store the current state into some cookie after each change and simply load them again on each page load.

我的一个天真的尝试是在每次更改后简单地将当前状态存储到某个 cookie 中,并在每次页面加载时再次加载它们。

回答by Ben Flynn

Along these lines, I had a page whose behavior I didn't want to repeat if refreshed, so I changed the hash programmatically as described in this answer.

沿着这些思路,我有一个页面,如果刷新我不想重复该页面的行为,因此我按照本答案中的描述以编程方式更改了哈希值。

checkRefresh: function() {
    if (document.location.hash === '#visited') {
        console.log('Refreshed');
        return true;
    } else {
        document.location.hash = 'visited';
        return false;
    }
}

UPDATE

更新

I found that at least Mobile Safari would ignore the hash if the refresh occurred automatically (e.g. page data expunged from cache before being viewed again). I ended up using a more complex solution described here.

我发现如果刷新自动发生(例如,在再次查看之前从缓存中删除的页面数据),至少 Mobile Safari 会忽略散列。我最终使用了此处描述的更复杂的解决方案。

回答by Capt Otis

Found this on the web for you...

网上找了这个给你...

Has both a javascript clever method along with a cookies method.

具有 javascript 智能方法和 cookie 方法。

http://www.tedpavlic.com/post_detect_refresh_with_javascript.php

http://www.tedpavlic.com/post_detect_refresh_with_javascript.php

回答by Nick

I was able to force the change event code to run on refresh by

我能够强制更改事件代码在刷新时运行

  window.onload = $.address.update(function(){    
...
})

回答by kingjeffrey

On a page refresh, the javascript is also reloaded. So couldn't you specify what you want to happen directly in jQuery's ready method?

在页面刷新时,javascript 也会重新加载。所以你不能直接在 jQuery 的 ready 方法中指定你想要发生的事情吗?