Thursday, September 11, 2008

Prevent multiple refresh button and multiple requests to server using javascript

Let me mention out at the start itself:- This post will help you prevent a stupid impatient user from sending multiple requests to your server. But a deliberate attack will go through without slightest of problems
Here is the scenario
You have a web application running on an slow server which can handle user requests simultaneously but when a impatient user starts hitting his refresh button million times a second, it leaves your server in a pity state. So how to go about?

Key is to use onbeforeunload event built into ie and Firefox browsers. But you would not want to trouble your users every time they want to leave a page. So key is to use a flag variable along with timeout function, check the code below:-

<title>Untitled Document</title>
<script language='javascript'>
var me = true;
function closeIt()
if(me == true) {me = false ; return;}
return "Server is still executing the previous request, Are you sure you wish to send another request?";
PUT a heavy server job here to actually test it

there are other methods to prevent the same, but most of them require to be taken care of while coding. This solution is useful when you already have an application ready but want a quick fix for the refresh button problem. If you are still in the coding stage of your application here is a more detailed way to implement it on server side for much more complete control

No comments: