李东's Blog

李东

web页面长时间未操作后,自动退出到登录页面

1930
2022-07-24
web页面长时间未操作后,自动退出到登录页面

用定时器记录鼠标的时间,到时间定时器自动走接口退出

<script type="text/javascript">
        var lastTime = new Date().getTime();
            var currentTime = new Date().getTime();
            var timeOut = 10 * 60 * 1000; //设置超时时间: 10分
            $(function(){
                /* 鼠标移动事件 */
                $(document).mouseover(function(){
                    lastTime = new Date().getTime(); //更新操作时间
                });
            });
            function testTime(){
                currentTime = new Date().getTime(); //更新当前时间
                    if(currentTime - lastTime > timeOut){ //判断是否超时 超时就访问退出接口
                         $.ajax({
                            url:"admin/logout",
                            dataType:"json",
                            type:"get",
                            async : false,
                            cache : false,
                            success:function(){
                                     // 退出登陆接口
                                    window.location.href="admin/login";
                            },
                            error:function(){
                            }
                        })
                    }
            }
            /* 定时器  间隔1秒检测是否长时间未操作页面  */
            window.setInterval(testTime, 1000);
    </script>