Display warning after X time of inactivity and log

2019-09-19 07:54发布

问题:

I have seen many answers similar to this question.None helped me resolving this. Issue- I want to display a warning message after 5 minutes of inactivity,If the user is still inactive post 5 minutes of warning, Page should automatically redirect to logoff.jsp. I dont want to use Jquery here.It has to be done using Javascript only. Help!!

var IDLE_TIMEOUT = 15; //seconds
 var _idleSecondsCounter = 0;

 document.onkeypress = function() 
 {
    _idleSecondsCounter = 0;
 };
 document.onclick = function() 
 {
    _idleSecondsCounter = 0;
 };
 document.onmousemove = function()
 {
    _idleSecondsCounter = 0;
 };

 window.setInterval(CheckIdleTime, 1000);

 function CheckIdleTime() {
    _idleSecondsCounter++;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        var answer = confirm("It's been long time you are idle.\nPlease click OK to continue session.\nTo close this session click Cancel.");
        if (answer) 
        {
            //document.location.href = "logout.html";   
            _idleSecondsCounter=0;
        }
        else{
            //window.open('', '_self', ''); window.close();
            document.location.href = "logoff.jsp";
        }

    }
 }

回答1:

Ah, you cannot programmatically close alert() or confirm() or these modals. You've to make your own kind of box if you want to do that.

When you show confirm(), your JS execution is automatically paused. So you'll need to create your custom dialog box using HTML/CSS.

function tempAlert(msg,duration)
{
    var el = document.createElement("div");
    el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
    el.innerHTML = msg;
    setTimeout(function(){
        el.parentNode.removeChild(el);
        // 5 minutes over. sign off user
    },duration);
    document.body.appendChild(el);
}

tempAlert("We're signing you off in 5 minutes",5*60000);