7月 20, 2017

『MVC JavaScript』TimeOut登出

在開發MVC的專案有時會需要畫面不動一段時間後要自動登出的功能,以下範例為10分鐘若鍵盤和滑鼠沒有在網頁上動作時,則登出的方法!



View(_Layout)

<script>

    inactivityTime ();
    function inactivityTime () {
        var t;
        window.onload = resetTimer;
        // DOM Events
        window.onmousemove = resetTimer;
        window.onkeypress = resetTimer;
        //window.onmousedown = resetTimer; // catches touchscreen presses
        //window.onclick = resetTimer;     // catches touchpad clicks
        //window.onscroll = resetTimer;    // catches scrolling with arrow keys

        function logout() {
            //alert("You are now logged out.")
            window.location = "/Account/LogOffAuto";
        }

        function resetTimer() {
            clearTimeout(t);
            var sessionTimeoutWarning = 10; //min
            var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
            t = setTimeout(logout, sTimeout);
            // 1000 milisec = 1 sec         
        }
    };


</script>

Controller

public ActionResult LogOffAuto()
{
    Session["User"] = null; //it's my session variable
    Session.Clear();
    Session.Abandon();
    FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
    return RedirectToAction("Login", "Account");
}


David Kung 2017/07/20




1 則留言:

Related Posts Plugin for WordPress, Blogger...