How to Prevent Users to Press F5 key (Refresh button)

Some times we want to prevent user to Press F5 key to prevent Page Refresh.
You can use the below script. Paste this code in the Head Section of your Page.
<script language=javascript>
document.onkeydown = function(){
if(window.event && window.event .keyCode == 116){
window.event.keyCode = 505; // Capture and remap F5
}
if(window.event && window.event .keyCode == 505){
// New action for F5
return false; // Must return false
}}
</script>

7 comments:

Anonymous said...

this code is not work me please send me some other code. my problem is that i have create one web application and i put one timer when timer reach at zero it show the msg "Time Up!".

But my problem is that when ever i press refresh button or F5 key timer starts with begin time.

i want that when ever page is refreshed time will not change it continuous with same time...

please help me out.

please send a solution on my email id :

nitinvaghela.333.ce@gmail.com

Anuj Rathi said...

Dear Nitin,
When you press F5, your page loads again. Means all vaiables that you set using javascript also reset. So you can't do this through javascript.You will have to store your timer value to server side & you can do this through AJAX easily.

Regards,
Anuj Rathi

abell said...

interesting...
but i think you couldn't have done this without knowing the keycodes...
so, do you know a site or something or a way to know the code for every key?

abell said...

it's me again :P
i adapted your code to mine and it's awesome. very useful when checking security and insertion issues.
but there's still one way to refresh the page by right-clicking and hitting the option "refresh".
do you know some way of preventing this?

Anonymous said...

Hi Anuj,

Your script works fine, thanks.
However, if you press Ctrl+R the pages refreshes anyway.

Do you think you could modify your script to avoid this?

Thanks and regards,

Enrique

Anuj Rathi said...

Dear Abell,
If u wan to avoid Mouse Right Click, then u can use my another script by which u can avoide right mouse click. So no one will be able to refresh the page (using F5 or with right mouse click)

http://anujkrathi.blogspot.com/2007/06/how-to-prevent-right-mouse-click-in-ie.html

Regards,
Anuj Rathi

Anonymous said...

we can refresh the page in the browser using refresh button in the browser i.e. after address bar......how to avoid that??