sourcetip

일정 기간 비활성 상태가 지속된 후 자동으로 페이지를 다시 로드하는 방법

fileupload 2023. 4. 3. 21:42
반응형

일정 기간 비활성 상태가 지속된 후 자동으로 페이지를 다시 로드하는 방법

일정 기간 동안 페이지에 액티비티가 없을 경우 웹 페이지를 자동으로 새로고침하려면 어떻게 해야 합니까?

이 작업은 javascript 없이 다음 메타태그를 사용하여 수행할 수 있습니다.

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

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

하지만 당신은 활동이 없다면 어떤 활동을 하겠습니까?

활동이 없는 경우 페이지를 새로 고치려면 활동을 정의하는 방법을 파악해야 합니다.예를 들어, 누군가가 키를 누르거나 마우스를 움직이지 않는 한, 1분 간격으로 페이지를 갱신한다고 합시다.이벤트 바인딩에 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>

jquery가 필요 없는 완전한 javascript 솔루션도 구축했습니다.플러그인으로 바꿀 수 있을지도 몰라액체 자동 리프레쉬에 쓰긴 하는데 도움이 될 것 같네요

JSFidle 자동 새로 고침

// 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>

리셋하지 않는 한, 상기의 페이지는 10분마다 갱신됩니다.Timeout()이 호출됩니다.예를 들어 다음과 같습니다.

<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);

, 이 에서는 「」를 사용하고 있는 것이 .setIntervalsetTimeout이 때문에, 코드가 보다 콤팩트하게 됩니다.

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'";.

확인 ALERT 메시지 포함:

<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();">

조금 해 냈는데, 그 이 있다. 왜냐하면setInterval정확하지 않습니다.set를 참조해 주세요.인터벌 타이밍이 서서히 어긋나기 때문에 정확한 상태를 유지할 수 없습니다.

// Based on https://stackoverflow.com/a/15279599

// Refresh Rate is how often you want to refresh the page
// based off the user inactivity (in seconds).
var refresh_after = 20;
var last_user_action = new Date();

// Reset the Timer on users last action
function reset() {
    last_user_action = new Date();
}

// Countdown that executes every second.
setInterval(function () {
    refreshCheck();
}, 1000);

// The code that checks if the window needs to reload
function refreshCheck() {
    var expire_time = new Date(last_user_action);
    expire_time.setSeconds(expire_time.getSeconds() + refresh_after);
    now = new Date();
    if (now.getTime() >= expire_time.getTime() && document.readyState == "complete") {
        window.location.href = window.location.href; // We do this to discard the POST data.
    }
}

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);

그래, 그럼 에이잭스 기술을 써야지특정 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>

는는 i i i i i i i i iactivity사용자가 창에 집중하고 있는지 여부입니다.예를 들어, 한 창에서 다른 창(예: Google Chrome에서 iTunes로, 또는 인터넷 브라우저 내에서 탭 1에서 탭 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>

바디 코드는 두 솔루션에서 동일합니다.

<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>

LocalStorage를 사용하여 마지막 액티비티를 추적하면 새로고침 함수를 다음과 같이 작성할 수 있습니다.

function reloadPage(expiryDurationMins) {
    const lastInteraction = window.localStorage.getItem('lastinteraction')
    if (!lastInteraction) return // no interaction recorded since page load
    const inactiveDurationMins = (Date.now() - Number(lastInteraction)) / 60000
    const pageExpired = inactiveDurationMins >= expiryDurationMins
    if (pageExpired) window.location.reload()
}

그런 다음 마지막 상호 작용 시간을 밀리초 단위로 저장하는 화살표 함수를 만듭니다(String).

const saveLastInteraction = () => window.localStorage.setItem('last', Date.now().toString())

, 그럼 이제 ''를 한 번 들어봐야겠네요.beforeunload를 하여 ""lastinteraction무한 새로고침 루프에 빠지지 않도록 기록하십시오.

window.addEventListener('beforeunload', () => window.localStorage.removeItem('lastinteraction'))

감시해야 할 사용자 액티비티 이벤트는 다음과 같습니다.mousemove ★★★★★★★★★★★★★★★★★」keypress

window.addEventListener('mousemove', saveLastInteraction)
window.addEventListener('keypress', saveLastInteraction)

청취자를 '마지막 청취자'를 사용합니다.load 로드 시 합니다. '페이지 로드'setInterval일정 기간이 지난 후 페이지가 만료되었는지 확인하는 기능입니다.

const expiryDurationMins = 1

window.addEventListener('load', setInterval.bind(null, reloadPage.bind(null, expiryDurationMins), 1000))

이렇게 하고 있습니다.

let lastActionTaken = new Date().getTime();
function checkLastAction() {
  let now = new Date().getTime();
  if (now - lastActionTaken > 1000 * 60 * 60) window.location.reload();
  else lastActionTaken = now;
}
window.addEventListener("mousemove", checkLastAction);
window.addEventListener("touchstart", checkLastAction);
window.addEventListener("keydown", checkLastAction);

그러면 마우스를 이동하거나 키를 누르거나 터치스크린을 터치하는 즉시 페이지가 새로고침됩니다.이렇게 ,, 이, 이, 이, 이, 이, also, also, also, also, also.focus 이 으로 때window새로고침이 됩니다.이는 오래된 데이터가 표시되지 않는 것이 포인트이기 때문입니다.

다른 답변의 대부분은 "활동 없이" 질문의 주요 부분에 답변하지 않거나, 믿을 수 없을 정도로 복잡합니다.승인된 답변(여기서: https://stackoverflow.com/a/4644315/9008140 )을 사용하여 변수에 타이머를 할당할 수 있다는 점을 활용하기 위해 수정했습니다.이것에 의해, 타임 스탬프 뿐만이 아니라, 2번째의 타이머를 삭제할 수 있습니다.

/**
* create a timer that refreshes the page after the number of 
  minutes has passed without user interaction.
* Moving the mouse or pressing a key on the current page will start 
  the timer over.
* @param {any} minutes
*/
var refreshTimer;
function setPageRefreshTimer(minutes) {
    var refreshInterval = minutes * 60 * 1000; //interval is in milliseconds.  We refresh every x minutes.
$(document.body).bind("mousemove keypress", function (e) {
    if (refreshTimer != null && refreshTimer != undefined) {
        window.clearTimeout(refreshTimer);
    }
    refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
});
refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);

}

이 샘플 코드는 전달된 파라미터에 따라 몇 분 안에 갱신되며 Javascript 타이머만큼 정확합니다.테스트에서는 항상 1초 미만입니다.기능으로서 작성했습니다만, 괜찮으시다면, 페이지내에 끌어다 놓으셔도 됩니다.

이 작업은 html 헤더 섹션에 있는 코드를 따라 쉽게 사용할 수 있습니다.

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

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

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

반응형