IT

일정 시간 동안 작업이 없으면 자동으로 페이지를 다시로드하는 방법

lottoking 2020. 6. 21. 19:14
반응형

일정 시간 동안 작업이 없으면 자동으로 페이지를 다시로드하는 방법


일정 기간 동안 페이지에 활동이없는 경우 웹 페이지를 자동으로 다시로드하려면 어떻게합니까?


활동이없는 경우 페이지를 새로 고치려면 활동을 정의하는 방법을 알아야합니다. 누군가가 키를 누르거나 마우스를 움직이지 않는 한 매분마다 페이지를 새로 고칩니다. 이벤트 바인딩에 jQuery를 사용합니다.

<script>
     var time = new Date().getTime();
     $(document.body).bind("mousemove keypress", function(e) {
         time = new Date().getTime();
     });

     function refresh() {
         if(new Date().getTime() - time >= 60000) 
             window.location.reload(true);
         else 
             setTimeout(refresh, 10000);
     }

     setTimeout(refresh, 10000);
</script>

이 메타 태그를 사용하면 자바 스크립트없이 수행 할 수 있습니다.

<meta http-equiv="refresh" content="5" >

여기서 content = "5"는 페이지가 새로 고침 될 때까지 기다리는 시간 (초)입니다.

그러나 활동이없는 경우에만 어떤 종류의 활동을 하시겠습니까?


jquery가 필요없는 완벽한 자바 스크립트 솔루션을 만들었습니다. 플러그인으로 바꿀 수 있습니다. 유동적 인 자동 새로 고침에 사용하지만 여기에 도움이 될 것 같습니다.

JSFiddle 자동 새로 고침

// Refresh Rate is how often you want to refresh the page 
// bassed off the user inactivity. 
var refresh_rate = 200; //<-- In seconds, change to your needs
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
// If the user loses focus on the browser to many times 
// we want to refresh anyway even if they are typing. 
// This is so we don't get the browser locked into 
// a state where the refresh never happens.    
var focus_margin = 10; 

// Reset the Timer on users last action
function reset() {
    last_user_action = 0;
    console.log("Reset");
}

function windowHasFocus() {
    has_focus = true;
}

function windowLostFocus() {
    has_focus = false;
    lost_focus_count++;
    console.log(lost_focus_count + " <~ Lost Focus");
}

// Count Down that executes ever second
setInterval(function () {
    last_user_action++;
    refreshCheck();
}, 1000);

// The code that checks if the window needs to reload
function refreshCheck() {
    var focus = window.onfocus;
    if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
        window.location.reload(); // If this is called no reset is needed
        reset(); // We want to reset just to make sure the location reload is not called.
    }

}
window.addEventListener("focus", windowHasFocus, false);
window.addEventListener("blur", windowLostFocus, false);
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);

<script type="text/javascript">
  var timeout = setTimeout("location.reload(true);",600000);
  function resetTimeout() {
    clearTimeout(timeout);
    timeout = setTimeout("location.reload(true);",600000);
  }
</script>

resetTimeout ()이 호출되지 않으면 위의 10 분마다 페이지를 새로 고칩니다. 예를 들면 다음과 같습니다.

<a href="javascript:;" onclick="resetTimeout();">clicky</a>

허용 된 arturnt의 답변을 기반으로합니다. 이것은 약간 최적화 된 버전이지만 본질적으로 동일한 기능을 수행합니다.

var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function () {
    time = new Date().getTime();
});

setInterval(function() {
    if (new Date().getTime() - time >= 60000) {
        window.location.reload(true);
    }
}, 1000);

차이점은이 버전은 setInterval대신에 setTimeout코드를 사용 한다는 점입니다 .


var bd = document.getElementsByTagName('body')[0];
var time = new Date().getTime();

bd.onmousemove = goLoad;
function goLoad() {
if(new Date().getTime() - time >= 1200000) {
    time = new Date().getTime();
    window.location.reload(true);
    }else{
        time = new Date().getTime();
    }
}

마우스를 움직일 때마다 마우스를 마지막으로 움직일 때 확인합니다. 시간 간격이 20 분을 초과하면 페이지가 다시로드되고 마지막으로 이동 한 마우스는 갱신됩니다.


JavaScript setInterval메소드를 사용하십시오 .

setInterval(function(){ location.reload(); }, 3000);

선택한 대상으로 자동 새로 고침 이 경우 대상은 _self자체 설정되지만 window.open('self.location', '_self');코드를이 예제와 같이 간단히 변경하여 다시로드 페이지를 변경할 수 있습니다 window.top.location="window.open('http://www.YourPageAdress.com', '_self'";.

확인 경고 메시지와 함께 :

<script language="JavaScript">
function set_interval() {
  //the interval 'timer' is set as soon as the page loads  
  var timeoutMins = 1000 * 1 * 15; // 15 seconds
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  itimer=setInterval("auto_logout()",timeoutMins);
  atimer=setInterval("alert_idle()",timeout1Mins);

}

function reset_interval() {
  var timeoutMins = 1000 * 1 * 15; // 15 seconds 
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  //resets the timer. The timer is reset on each of the below events:
  // 1. mousemove   2. mouseclick   3. key press 4. scrolling
  //first step: clear the existing timer
  clearInterval(itimer);
  clearInterval(atimer);
  //second step: implement the timer again
  itimer=setInterval("auto_logout()",timeoutMins);
  atimer=setInterval("alert_idle()",timeout1Mins);
}

function alert_idle() {
    var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
    if (answer){

        reset_interval();
    }
    else{
        auto_logout();
    }
}

function auto_logout() {
  //this function will redirect the user to the logout script
  window.open('self.location', '_self');
}
</script>

확인 알림이없는 경우 :

<script language="JavaScript">
function set_interval() {
  //the interval 'timer' is set as soon as the page loads  
  var timeoutMins = 1000 * 1 * 15; // 15 seconds
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  itimer=setInterval("auto_logout()",timeoutMins);

}

function reset_interval() {
  var timeoutMins = 1000 * 1 * 15; // 15 seconds 
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  //resets the timer. The timer is reset on each of the below events:
  // 1. mousemove   2. mouseclick   3. key press 4. scrolling
  //first step: clear the existing timer
  clearInterval(itimer);
  clearInterval(atimer);
  //second step: implement the timer again
  itimer=setInterval("auto_logout()",timeoutMins);
}


function auto_logout() {
  //this function will redirect the user to the logout script
  window.open('self.location', '_self');
}
</script>

본문 코드는 두 솔루션 모두에서 동일합니다.

<body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">

이 작업은 HTML 헤더 섹션에서 다음 코드를 사용하는 것이 매우 쉽습니다.

<head> <meta http-equiv="refresh" content="30" /> </head>

30 초 후에 페이지가 새로 고쳐집니다.


예, Ajax 기술을 사용해야합니다. 특정 HTML 태그의 내용을 변경하려면 :

 <html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <title>Ajax Page</title>
        <script>
        setInterval(function () { autoloadpage(); }, 30000); // it will call the function autoload() after each 30 seconds. 
        function autoloadpage() {
            $.ajax({
                url: "URL of the destination page",
                type: "POST",
                success: function(data) {
                    $("div#wrapper").html(data); // here the wrapper is main div
                }
            });
        }
        </script>
    </head>
    <body>
    <div id="wrapper">
    contents will be changed automatically. 
    </div>
 </body>
 </html>

activity사용자가 창에 집중하는지 여부를 고려 하고 싶습니다 . 예를 들어, 한 창에서 다른 창으로 클릭하면 (예 : 인터넷 브라우저에서 Chrome에서 iTunes로 또는 Tab 1에서 Tab 2로) 웹 페이지에서 "초점이 없습니다!"라는 콜백을 보낼 수 있습니다. 또는 "초점입니다!" jQuery를 사용하여 이러한 가능한 활동 부족을 활용하여 원하는 작업을 수행 할 수 있습니다. 내가 당신의 위치에 있다면, 나는 다음 코드를 사용하여 매 5 초마다 초점을 확인하고 초점이 없으면 다시로드합니다.

var window_focus;
$(window).focus(function() {
    window_focus = true;
}).blur(function() {
    window_focus = false;
});
function checkReload(){
    if(!window_focus){
        location.reload();  // if not focused, reload
    }
}
setInterval(checkReload, 5000);  // check if not focused, every 5 seconds

그리고 가장 간단한 해결책은 다음과 같습니다.

경고 확인 포함 :

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout("IdleWarning()", timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Show idle timeout warning dialog.
    function IdleWarning() {
        var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
            if (answer){

                ResetTimers();
            }
            else{
                IdleTimeout();
            }
    }       

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

경고 확인없이 :

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout(timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

본문 코드는 두 솔루션 모두에 대한 SAME입니다

<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">

경고 대신 페이지 확인 텍스트 포함

이것이 비활성화되면 자동로드하는 또 다른 방법이므로 두 번째 대답을합니다. 이것은 더 간단하고 이해하기 쉽습니다.

페이지에서 새로 고침 확인

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5100; // 5,1 seconds
var warnPeriod = 5000; // 5 seconds
// Warning period should always be a bit shorter then time period

function promptForClose() {
autoCloseDiv.style.display = 'block';
autoCloseTimer = setTimeout("definitelyClose()", warnPeriod);
}


function autoClose() {
autoCloseDiv.style.display = 'block'; //shows message on page
autoCloseTimer = setTimeout("definitelyClose()", timePeriod); //starts countdown to closure
}

function cancelClose() {
clearTimeout(autoCloseTimer); //stops auto-close timer
autoCloseDiv.style.display = 'none'; //hides message
}

function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("promptForClose()", timePeriod); //restarts timer from 0
}


function definitelyClose() {

// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');

// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');

window.top.location=self.location;
}
-->
</script>

페이지 내 확인과 함께 사용할 때 확인 상자

<div class="leftcolNon">
<div id='autoCloseDiv' style="display:none">
<center>
<b>Inactivity warning!</b><br />
This page will Reloads automatically unless you hit 'Cancel.'</p>
<input type='button' value='Load' onclick='definitelyClose();' />
<input type='button' value='Cancel' onclick='cancelClose();' />
</center>
</div>
</div>

둘 다의 본문 코드는 동일합니다

<body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">

참고 : 페이지 내 확인을 원하지 않으면 확인없이 사용하십시오.

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000; // 5 seconds

function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("definitelyClose()", timePeriod); //restarts timer from 0
}

function definitelyClose() {

// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');

// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');

window.top.location=self.location;
}
-->
</script>

참고 URL : https://stackoverflow.com/questions/4644027/how-to-automatically-reload-a-page-after-a-given-period-of-inactivity

반응형