Javascript 如何使用超时对话框JS在Mousemove或Keydown事件中保持会话活动?

Javascript 如何使用超时对话框JS在Mousemove或Keydown事件中保持会话活动?,javascript,jquery,timeout-dialog.js,Javascript,Jquery,Timeout Dialog.js,我在应用程序中使用timeout-dialog.JS使非活动用户的会话在5分钟后过期。但我有一个输入网格,用户可以添加多个记录,然后在添加后,比如说10个记录,他去保存,但他花了5分钟以上输入所有这些细节,当他去保存或当他说是让我登录超时对话框时,屏幕重新加载,他丢失了所有数据 我想要的是,如果他移动鼠标或按键,会话应该被重置 为了实现这一点,我尝试在布局页面中添加mousemove和keydown事件,如下所示: <script> $(function () {

我在应用程序中使用timeout-dialog.JS使非活动用户的会话在5分钟后过期。但我有一个输入网格,用户可以添加多个记录,然后在添加后,比如说10个记录,他去保存,但他花了5分钟以上输入所有这些细节,当他去保存或当他说是让我登录超时对话框时,屏幕重新加载,他丢失了所有数据

我想要的是,如果他移动鼠标或按键,会话应该被重置

为了实现这一点,我尝试在布局页面中添加mousemove和keydown事件,如下所示:

     <script>
    $(function () {
        var fnTimeOut = function () {
            $.timeoutDialog.setupDialogTimer({
                timeout: 300,
                countdown: 60,
                logout_redirect_url: '@Url.Action("LogOff", "Account")',
                keep_alive_url: '@Url.Action("Keepalive", "Account")'
            });
        };
        fnTimeOut();

        $(this).mousemove(function () {
            $.timeoutDialog.setupDialogTimer({
                timeout: 300,
                countdown: 60,
                logout_redirect_url: '@Url.Action("LogOff", "Account")',
                keep_alive_url: '@Url.Action("Keepalive", "Account")'
            });             
        });

        $(this).keydown(function () {
            $.timeoutDialog.setupDialogTimer({
                timeout: 300,
                countdown: 60,
                logout_redirect_url: '@Url.Action("LogOff", "Account")',
                keep_alive_url: '@Url.Action("Keepalive", "Account")'
            });          
        });
    });
</script>

$(函数(){
var fnTimeOut=函数(){
$.timeoutDialog.setupDialogTimer({
超时:300,
倒计时:60,
注销\重定向\ url:'@url.Action(“注销”,“帐户”),
保持你的活力url:“@url.Action(“Keepalive”,“Account”)”
});
};
fn超时();
$(this).mousemove(函数(){
$.timeoutDialog.setupDialogTimer({
超时:300,
倒计时:60,
注销\重定向\ url:'@url.Action(“注销”,“帐户”),
保持你的活力url:“@url.Action(“Keepalive”,“Account”)”
});             
});
$(此).keydown(函数(){
$.timeoutDialog.setupDialogTimer({
超时:300,
倒计时:60,
注销\重定向\ url:'@url.Action(“注销”,“帐户”),
保持你的活力url:“@url.Action(“Keepalive”,“Account”)”
});          
});
});
但这给了我一个警告,说页面没有响应KILL或WAIT选项

那么,有没有什么方法可以在mousemove和keydown事件上使用timeout dialog JS重置会话

任何帮助都将不胜感激。
谢谢。

像这样的原始
mousemove
事件监听器对于您来说太过分了,因为它每秒可以发出数百个事件,如果您执行更重的操作,它肯定会杀死您的应用程序。我可以看到你可以做两件事:

  • 限制事件,使其每N秒仅执行一次->请参阅
  • 找到一种只重置超时对话框内部计时器的方法。查看源代码内部,看看API中是否有任何东西可以做到这一点,而不是每次都设置一个全新的对话框(我怀疑这是没有效率的)。如果你需要进一步的帮助,请告诉我
如果您只想保持后端会话处于活动状态,可以按如下方式调用您的保持活动url:

var callKeepAlive = _.throttle(function () {
  $.get( "<YOUR KEEP-ALIVE URL>", function( data ) {
    console.log('keep-alive called')
  });
}, 1000);
var callKeepAlive=\节流阀(函数(){
$.get(“),函数(数据){
console.log('keep-alive called')
});
}, 1000);

然后在mousemove/keyup事件侦听器中,执行
callKeepAlive()

我在检查XMLHttp的一些浏览器兼容性时遇到了这个问题,并为此在此处随机添加了浏览器线程。我想我会给我的工作的例子,我想出了,因为我需要类似的东西很快,并认为这个问题可以做一个更大的例子

底部的最小代码

请原谅我有点混乱,这是一个原始的例子

<?php
    // Do not forget session start if copying into your own code..
    if (isset($_GET['keepalive'])) {
        header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        header('Content-Type: application/json');
        $boolStatusOfSession = TRUE;        // Something like: $boolStatusOfSession = (isset($_SESSION['MyTokenWhenSignedIn']) ? TRUE : FALSE);
        echo json_encode(array('status'=>$boolStatusOfSession));
        exit;
    }
?>
<html>
    <head></head>
    <body>
        <p>This script will throttle the mouse movement event to a rate of once per second max and perform a keep alive request to the same page along with a json response of the session status</p>
        <p id="debugbox"><b>Server Keep Alive: </b>please wait for the timer (10 seconds)</p>
        <p id="debugbox2"></p>

        <script>
            var elmDebug = document.getElementById('debugbox');
            var elmDebug2 = document.getElementById('debugbox2');
            var idleStart = Math.floor(Date.now() / 1000);

            function keepAlivePoster() {
                objHttp = new XMLHttpRequest();
                objHttp.onreadystatechange = function() {
                    var strDebug = "<b>Server Keep Alive: </b> ";
                    if (objHttp.readyState == XMLHttpRequest.DONE) {
                        idleStart = Math.floor(Date.now() / 1000);  
                        objResp = JSON.parse(objHttp.responseText);
                        if (objResp.hasOwnProperty('status') && objResp.status == true) {
                            // DO STUFF HERE WHEN SIGNED IN (Or do nothing at all)
                            strDebug += "Signed In, ";
                        } else {
                            // DO STUFF HERE WHEN SIGNED OUT (A window reload if your page can handle the session change)
                            strDebug += "Signed Out, "; // Or does not exist / error.. best to use a int status
                        }
                    }
                    elmDebug.innerHTML = strDebug + "Updated at " + Math.floor(Date.now() / 1000);
                    elmDebug2.innerHTML = '<b>Mouse Move Event: </b> Idle timer reset to ' + idleStart;
                }
                objHttp.open('GET', '?keepalive');
                objHttp.send(null);
            };


            function throttleController (callback, limit) {     // TAKEN FROM: https://jsfiddle.net/jonathansampson/m7G64/
                var wait = false;                  // Initially, we're not waiting
                elmDebug2.innerHTML = '<b>Mouse Move Event: </b> Idle timer reset to ' + idleStart;
                return function () {               // We return a throttled function
                    if (!wait) {                   // If we're not waiting
                        callback.call();           // Execute users function
                        wait = true;               // Prevent future invocations 
                        setTimeout(function () {wait = false;}, limit); // After a period of time, allow future invocations again
                    }
                }
            }           
            window.addEventListener("mousemove", throttleController(keepAlivePoster, 10000));       // Allow "idleCallback" to run at most 1 time every 10 seconds

        </script>
    </body>
</html>
对于要涵盖的任何其他事件,您将复制的最后一行,当您使用多个事件时,您还将希望使wait变量位于更高的作用域/全局上

为什么选择php状态/代码

function keepAlivePoster() {
    objHttp = new XMLHttpRequest();
    objHttp.open('GET', '?keepalive');
    objHttp.send(null);
};
function throttleController (callback, limit) {     // TAKEN FROM: https://jsfiddle.net/jonathansampson/m7G64/
    var wait = false;  return function () {              
        if (!wait) { callback.call();  wait = true; setTimeout(function () {wait = false;}, limit); }
    }
}           
window.addEventListener("mousemove", throttleController(keepAlivePoster, 10000));

首先是在html生成之前包含的另一个文件中。。但理想情况下,您希望GET请求尽可能小,并且有一些规则等等。。因此,我已经禁用了缓存页面的功能,浏览器可以轻松使用json响应,同时提供了一个简单的检查,以便在需要时重定向/重新加载。

John Smith感谢您的响应。有没有办法我可以直接调用keep_alive_url,这样它就可以让我的会话保持活动状态。这听起来有效吗?我已经编辑了我的答案,试着用这个方法玩一下。这个方法中的油门是什么?油门将确保keep alive只能每1000毫秒调用一次。因此,您不会在每个鼠标移动事件(将有数百个)上调用keep alive。