Skip to main content

How to detect browser closing events and warn user before closing


Recently I came across this problem.I was creating a web application where users were supposed to save their work before logging out.While testing, it turned out that many users closed their browsers instead of logging out.

To solve this, I googled the problem and found out that this was a very common problem.

I just used below java script code in my webpage's header.

Q. How to detect browser closing event and save your data
Ans:



The onunload event gets fired when the browser is closed or refreshed(using F5 or the refresh button).

So now It turns out that the data was getting saved unnecessarily on refreshing the page.
For that I stumbled across a forum where I found the solution.(It works for IE only)

Q.How to disable function key F5?
Ans:
document.attachEvent("onkeydown", my_onkeydown_handler); 
function my_onkeydown_handler() 
{ 
          switch (event.keyCode) 
            { 


                case 116 : // 'F5'
                event.returnValue = false; 
                event.keyCode = 0; 
                window.status = "F5 is disabled"; 
                break; 
            }
}

This disabled the F5 key .Also, the status bar in the browser gets the status "F5 is disabled".


Now it turns out that the user closes the browser and his data gets unknowingly saved!
So Now I had to warn the user before saving the data and closing the window.
Google to the rescue again..(as always)

Here's the solution

Q.How to warn user before closing the browser?
Ans:

 
I choose the warning message for my application as
"If you continue, the changes will be saved."

For the onbeforeunload event, the string that you return is shown along with the default IE message.




So here is my complete solution:

The javascript snippet:

window.onunload =function()
 {
     //Save the data here before exiting
  
 }


window.onbeforeunload = function() {
                      // return 'My Warning message.'   
                     //UNCOMMENT ABOVE LINE AND put your warning message
}



document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler()
{
          switch (event.keyCode)
            {

                case 116 : // 'F5'
                event.returnValue = false;
                event.keyCode = 0;
                window.status = "F5 is disabled";
                break;
            }
}



Comments

Popular posts from this blog

How to convert a CSV file to XLSX

I wrote this utility for a friend of mine who wanted to convert large (~50MB) CSV files to XLSX. The CSV files had comma "," as a delimiter. I have used apache poi utility in this program. https://www.apache.org/dyn/closer.lua/poi/release/RELEASE-NOTES.txt This code uses SXSSFWorkbook class. The SXSSFWorkbook class uses "BigGridDemo" strategy, where only portions being processed are kept in memory. There are temporary files created which store the rest of the temporary data. setCompressTempFiles() method allows these temp files to be compressed. The size of these files can get quite large. The data to be converted was UTF-8 encoded data. So, we are using  OutputStreamWriter, where we specify the encoding of the data. If you do not need the encoding, just remove that parameter from the constructor call of OutputStreamWriter. The system where this ran, supported Java 7, so have not used features in java 8, such as try with exceptions. import java.io.*; im...

Five most useful spring modules

  Java Spring framework is one of the popular java frameworks. A thread on 5 commonly used spring modules 1. Spring Boot and Spring MVC These modules makes it easy and quick to create stand-alone, production-grade Spring based Applications that you can "just run". Example Use:- A RESTful service with self-container server. 2. Spring Batch This module is used to build batch applications that need to recurrently process large volumes of data. Features: Chunk based processing, retry, skip Example Use:- Everyday, read data of daily trades from database and update the credit on customer's accounts. 3.Spring Data Provides a spring based programming model for accessing data. This module has very powerful features and supports wide range of databases. Example Use:- Read, Write data from PostgreSQL for your application. 4.Spring Cloud Provides tools for developers to quickly build some of the common patterns of distributed systems. Libraries for Service registration and discovery,...

Five important aspects of microservices

  5 important aspects/components of microservices architecture 1. Microservices - Services that are built small enough so that their entire lifecycle can be owned and managed by a small team. 2. Service Discovery - A mechanism of how microservices can locate each other over network.  Example : if Microservice A wants to call microservice B:  It will use service discovery mechanism to fetch IP address and port of B and then call B. Implementations : ZooKeeper, Consul, etcd, Eureka 3. External configuration - Enable services to run on various environments without a code modification inside the service. Enable different configuration values for those services for different environments.  Dynamically change configurations without changing application code or restart/redeploy application. Example - DB credentials and other details, application properties, environment variables for Dev, QA and Prod env. Implementations : Consul, Spring cloud (enables various datastores ...