检测浏览器刷新 [英] Detect browser refresh

查看:44
本文介绍了检测浏览器刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何知道用户是否按下 F5 来刷新我的页面(类似于 SO 的实现方式.如果刷新页面,问题计数器不会增加).我已经测试了十几个教程中提到的许多代码片段,但没有一个能正常工作.

How can I find out if the user pressed F5 to refresh my page (Something like how SO implemented. If you refresh your page, the question counter is not increased). I have tested many code snippets mentioned in a dozen of tutorials, but none worked correctly.

更清楚地说,假设我有一个空的 Web 表单,并且想检测用户是否在客户端按下了 F5(导致刷新未提交).

To be more clear, suppose that i have an empty web form and would like to detect whether the user has pressed F5 in client-side (causing a refresh not submit) or not.

我可以使用会话变量,但是如果用户导航到我网站的另一个页面,然后又回来了,我想将其视为新访问,而不是刷新.所以这不是会话范围变量.

I can use session variables, but if the user navigates to another page of my site, and then comes back , I'd like to consider it as a new visit, not a refresh. so this is not a session-scope variable.

谢谢.

更新:我能找到的唯一解决方法是从基页继承我的页面,覆盖如下所示的加载方法:

Update: The only workaround I could find was to inherit my pages from a base page, override the load method like below:

    public class PageBase : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.Session["LastViewedPage"] = Request.RawUrl;
    }
}  

如果我有兴趣知道这是否是刷新,则在每个页面中:

and in every page if I was interested to know if this is a refresh:

if (this.Session["LastViewedPage"].ToString() == Request.RawUrl)
{
    // This is a refresh!
}

推荐答案

唯一确定的解决方案是使 重定向到同一页面,这里有一个类似的问题:使用 ASP.NET 重定向后获取

但还有一些其他技巧,通过在页面上添加一些票证,看看这是相同的还是有变化的,请参阅完整的示例和代码:

But there are also some other tricks, by adding some ticket on the page and see if this is the same or have change, see the full example and code at:

http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET

还有一个:

http://dotnetslackers.com/community/blogs/simoneb/archive/2007/01/06/Using-an-HttpModule-to-detect-page-refresh.aspx

这篇关于检测浏览器刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆