簡體   English   中英

如何知道用戶當前是否正在使用Javascript讀取頁面?

[英]How to know if a page is currently being read by the user with Javascript?

我正在創建一個包含動態內容的網頁,該網頁通過AJAX輪詢進入視圖。 頁面JS偶爾會下載更新的信息,並在用戶閱讀其他信息時將其呈現在頁面上。 這種事情對帶寬和處理時間來說代價很高。 我希望在沒有查看頁面時暫停輪詢。

我注意到我打開的大部分網頁花費了大部分時間,或者在未查看的標簽中。 我希望能夠暫停腳本,直到實際查看頁面。

我不知道該怎么做,它似乎試圖打破html DOM的沙箱並進入用戶的系統。 如果JS引擎不了解其渲染環境,則可能是不可能的。 我從來沒有見過不同的網站這樣做(不是用戶打算看到它......)

因此,我認為這是一個有趣的討論問題。 您如何編寫一個CPU重的Web應用程序,以便在不使用時暫停? 給用戶一個暫停按鈕是不可靠的,我希望它是自動的。

你最好的解決方案是這樣的:

 var inactiveTimer;
 var active = true;
 function setTimer(){
  inactiveTimer = setTimeOut("stopAjaxUpdateFunction()", 120000); //120 seconds
 }
 setTimer();
 document.onmouseover = function() { clearTimeout ( inactiveTimer ); 
                                     setTimer(); 
                                     resumeAjaxUpdate();
  }; //clear the timer and reset it.
 function stopAjaxUpdateFunction(){
  //Turn off AJAX update
  active = false;   
 }
 function resumeAjaxUpdate(){
  if(active == false){
   //Turn on AJAX update
   active = true;
  }else{
   //do nothing since we are still active and the AJAX update is still on.
  }    
 }

stopAjaxUpdateFunction應該停止AJAX更新進度。

設置“不活動超時”如何在每次在DOM中收到鼠標或鍵盤事件時重置? 我相信這就是大多數IM程序決定你“離開”的方式(盡管他們通過在系統級別掛鈎輸入消息來實現)

在研究項目之前,我已經研究過這個問題了。 當時(2 - 3年前)我沒有找到從瀏覽器獲取有關您是否被最小化的信息的方法:(

首先檢查窗口何時失去並獲得焦點。

window.onblur = function () { /* stop */ };
window.onfocus =  function () { /* start */ };

此外,由於各種原因,用戶可能停止閱讀頁面而不會使其失去焦點(例如,他起身並離開計算機)。 在這種情況下,您必須假設在一段時間不活動(沒有鼠標或鍵盤事件)后,用戶的注意力已離開頁面。 在另一個答案中描述了執行此操作的代碼。

我知道你已經接受了答案,但我個人會因為各種原因使用這里提到的幾個答案的組合,包括:

  • 使用鼠標事件只會疏遠熟悉基於鍵盤的瀏覽的用戶。
  • 使用模糊/焦點事件不允許去喝茶的用戶;-)

我最有可能使用以下內容作為指導:

var idleTimer, userIsIdle, pollingTimer;
document.onkeydown = document.onmousemove = resetTimer;

window.onload = function () {
    pollingTimer = window.setTimeout(runPollingFunction, 30000);
    resetTimer();

    /* IE's onblur/onfocus is buggy */ 
    if (window.navigator.appName == "Microsoft Internet Explorer")
        document.onfocusin  = resetTimer,
        document.onfocusout = setIdle;
    else
        window.onfocus = resetTimer,
        window.onblur = setIdle;
}
function resetTimer() {
    if (userIsIdle)
        setBack();

    window.clearTimeout(idleTimer);
    idleTimer = window.setTimeout(setIdle, 120000); // 2 minutes of no activity    
}
function setIdle() {
    userIsIdle = true;
    window.clearTimeout(pollingTimer); // Clear the timer that initiates polling
    window.clearTimeout(setIdle);
}
function setBack() {
    userIsIdle = false;
    runPollingFunction(); // call the polling function to instantly update page
    pollingTimer = window.setTimeout(runPollingFunction, 300000);
}

您可以收聽mousemove和keypress事件。 如果其中一個在過去X​​秒內被觸發,則繼續進行更新。 否則,請勿更新。

它並不完美,但我認為這是純JS最好的。

如果您想進入Flash,Silverlight或Java世界,您可以從瀏覽器中獲取更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM