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
Post a Comment
Have some feedback, comment or question ?
Post it here in comments section.