简体   繁体   中英

JavaScript - detecting if a POST request has occurred

I have a small problem: I need to detect if the user of my website has not carried out any Ajax POST request in a set time frame, and give him a prompt to do something about it. I already have a code as follows:

var idleCounter = 600
var loginTimeoutCounter = setInterval(function() {
    console.log(idleCounter)

    // If a POST request is detected, reset idleCounter to max value.

    if (idleCounter > 0) {
        idleCounter -= 1
    } else {
        var promptAboutLogout = confirm('You have been idle for more than 6 hours.\n\n' + 
       'Your login session could have expired by now.\n\n' + 
       'Please be sure to refresh this web page before attempting to upload new content.\n\n' +
       'Press OK to reload this page, or Cancel to stay on it as-is.')
    if (promptAboutLogout) {
        clearInterval(loginTimeoutCounter)
        location.reload()  // Reload the web page to refresh the login credentials.
    } else {
        idleCounter = 600   // Re-set the counter for 10 min to give user another prompt.
    }
  }
}, 1000)

I just cannot figure out how to neatly add in a code for POST request detection. I do not want to glue in idleCounter value modification in a form submit eventListener a few hundred lines earlier, because it will be messy, and difficult to come back to when the code will go through the next revision in any foreseeable future.

Is there any neat JS function which picks up occurrence of any POST request?

The approach you are using would make more sense if you want to prompt the user before the session is about to expire and not after the session has expired. However if you want to continue using this approach you should have a common controller/util(consider it a wrapper over the lib you are using for ajax requests) from where you fire all your ajax requests. So whenever you want to invoke an ajax request, you pass the details to the controller which in turn wil make the actual ajax request. It would then receive the response from server and pass it to the callee for further processing. Here you can handle your timer variable for every post request.

Now if your are using a common controller you can get rid of this timer thing all together. When the session will expire, you server will redirect to the login page, mostly with status code 302. Your browser will handle this redirect request and serve your ajax callback with the html of the login page. At this point you can prompt your message dialog or event better display the login screen so that user can reauthenticate and continue his work from there. This should be some amount of code change but should surely ease things in future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM