6

Possible Duplicate:
Prevent any form of page refresh using jQuery/Javascript

how can i prevent user to reload (refresh) html page using javascript or jquery.

after loading the page for the first time, i want to prevent user reload the page either by press F5 or refresh from browser or by any way.

Can i do that?

Note: i try window.onbeforeunload, but i didn't know how to stop window.onload event from it.

Any help?

Community
  • 1
  • 1
Georgian Citizen
  • 3,727
  • 6
  • 38
  • 46
  • 1
    This other SO page answers your question: http://stackoverflow.com/questions/3527041/prevent-any-form-of-page-refresh-using-jquery-javascript – C0deH4cker Jun 19 '12 at 05:36
  • 3
    _"using javascript or jquery"_ - Note: if it can't be done with JS then it can't be done with jQuery... – nnnnnn Jun 19 '12 at 05:40
  • i know that but i mean that if i can do that by jquery i better for me to do it by javascript – Georgian Citizen Jun 19 '12 at 05:53
  • C0deH4cker, i try http://stackoverflow.com/questions/3527041/prevent-any-form-of-page-refresh-using-jquery-javascript but after an alert asks me to stay in the page or leave it, if i choose stay it works fine, but if i choose leave it calls th onload event also, and that i don't need it – Georgian Citizen Jun 19 '12 at 05:58
  • @mbayloon you cant stop the page from reloading, if the user wants it to. Check out my answer below.. – gopi1410 Jun 19 '12 at 06:01

2 Answers2

9

It is not possible to stop the user from page reload/page close if the user wants it. Two methods which you can use are as follows:

You can ask for a confirmation like this:

<script>
window.onbeforeunload = function (e) {
e = e || window.event;

// For IE and Firefox prior to version 4
if (e) {
    e.returnValue = 'Sure?';
}

// For Safari
return 'Sure?';
};
</script>

Here is the fiddle for above: http://jsfiddle.net/gopi1410/NujmL/

You can preventDefault on pressing of F5 key using:

document.onkeydown = function(event) {
  if(window.event){
        event.preventDefault();
  }
}
gopi1410
  • 6,567
  • 9
  • 41
  • 75
7

No, you can't. If a user wants to reload a page you cannot stop them.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335