检测浏览器刷新
我如何知道用户是否按 F5 刷新我的页面(类似于 SO 的实现方式。如果刷新页面,问题计数器不会增加)。我已经测试了许多教程中提到的许多代码片段,但没有一个能正常工作。
更清楚地说,假设我有一个空的 Web 表单,并且想要检测用户是否在客户端按了 F5(导致刷新未提交)。
我可以使用会话变量,但如果用户导航到我网站的另一个页面,然后返回,我想将其视为新访问,而不是刷新。所以这不是会话范围变量。
谢谢。
更新:我能找到的唯一解决方法是从基页继承我的页面,重写加载方法,如下所示:
public class PageBase : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Session["LastViewedPage"] = Request.RawUrl;
}
}
以及在每个页面中,如果我有兴趣知道这是否是刷新:
if (this.Session["LastViewedPage"].ToString() == Request.RawUrl)
{
// This is a refresh!
}
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.
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.
Thanks.
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!
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了这个问题并使用以下代码。这对我来说效果很好。
I run into this problem and use the following code. It works well for me.
唯一确定的解决方案是重定向到同一页面 ,这是一个类似的问题:Post-Redirect-Get with ASP。 NET
但是还有一些其他技巧,通过在页面上添加一些票证并查看是否相同或有更改,请参阅完整的示例和代码:
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
The only sure solution is to make a redirect to the same page , and here is a similar question: Post-Redirect-Get with 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
and one more:
http://dotnetslackers.com/community/blogs/simoneb/archive/2007/01/06/Using-an-HttpModule-to-detect-page-refresh.aspx