How to Detect a Page Refresh

Certainly, you cannot control if the user refreshes the web page or directly close the web page. But, it's important to show a confirmation alert before closing the Tab. For instance,

1. You have seen in Shopping websites when you are in the middle of payment or you are paying the Bill and if you try to refresh the web page then it will show a confirm alert on the screen.

2. When the form has many fields and the user filled the form but somehow the Browser is being closed. Now, the user needs to again fill out that long form.

3. While students giving the online test and have not completed yet and try to close or refresh the page.

There are many other situations where you can use it. Sometimes you may want to detect if the page was refreshed using the "F5" key, right-click, and "Reload" or any other method available. Either way, this can be detected somehow from the server side. Let's see some useful ways below.

1. How to with PHP

In this snippet, I will show you how to do this with PHP.

$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
 
if($pageWasRefreshed ) {
  //do something because page was refreshed;
} else {
  //do nothing;
}

2. How to with Angular

If you want to detect the browser refresh with Angular, I will show you a simple way to do it.

You need to look at the Angular Router. Specifically to the navigated property. This property is false when the router starts and after the first navigation, it changes to true. And that's it.

// Example in the constructor of you App Component
constructor(private router: Router) {
  this.subscription = router.events.subscribe((event) => {
    if (event instanceof NavigationStart) {
      browserRefresh = !router.navigated;
    }
  });
}

3. How to with ASP.NET

In this example, I've put a Label and a Button on the page, on clicking the label and Text becomes Hello and when I refresh the page label's text again becomes Hello.

HTML SOURCE OF PAGE:

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<br />
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Button" /></div>
</form>
</body>
</html>

In the Page_Load event, I am creating a Session Variable and assigning System date and time to it, and in the Page_Prerender event, I am creating a Viewstate variable and assigning the Session variable's value to it.

Then, in the button's click event, I am checking the values of the Session variable and Viewstate variable if they both are equal then the page is not refreshed otherwise it has been refreshed.

C# Code:

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}

}

protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() ==
ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}

else
{
Label1.Text = "Page Refreshed";
}
}
 
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}

4. How to with JavaScript

In this section, I discuss how you can detect refresh using JavaScript.

onbeforeunload event trigger when trying to close, refresh the tab, or close the Browser. You can use this to display an alert message on the Browser for this you only need to return your message text.

<script type="text/javascript">
 window.onbeforeunload = function () {
  return 'Are you really want to perform the action?';
 }
</script>

You can also perform in this way also.

<body onbeforeunload=" return 'Are you really want to perform the action?'">


Leave a reply



Submit