Prevent any form of page refresh using jQuery/Javascript

pankaj picture pankaj · Aug 20, 2010 · Viewed 235.7k times · Source

Once the user is on my page, I do not want him to refresh the page.

  1. Anytime, the user hits F5 or refresh button on top. He should get an alert saying

    You cannot refresh the page.

  2. Also if the user opens a new tab and tries to access the same url in prev tab he should get an alert

    You cannot open same page in 2 tabs

Anyway I can do this using JavaScript or jQuery? Point one is really important.

Answer

Seth picture Seth · Aug 20, 2010

#1 can be implemented via window.onbeforeunload.

For example:

<script type="text/javascript">
    window.onbeforeunload = function() {
        return "Dude, are you sure you want to leave? Think of the kittens!";
    }
</script>

The user will be prompted with the message, and given an option to stay on the page or continue on their way. This is becoming more common. Stack Overflow does this if you try to navigate away from a page while you are typing a post. You can't completely stop the user from reloading, but you can make it sound real scary if they do.

#2 is more or less impossible. Even if you tracked sessions and user logins, you still wouldn't be able to guarantee that you were detecting a second tab correctly. For example, maybe I have one window open, then close it. Now I open a new window. You would likely detect that as a second tab, even though I already closed the first one. Now your user can't access the first window because they closed it, and they can't access the second window because you're denying them.

In fact, my bank's online system tries real hard to do #2, and the situation described above happens all the time. I usually have to wait until the server-side session expires before I can use the banking system again.