Programing

브라우저 창이 현재 활성화되어 있지 않은지 감지하는 방법이 있습니까?

lottogame 2020. 10. 4. 10:19
반응형

브라우저 창이 현재 활성화되어 있지 않은지 감지하는 방법이 있습니까?


주기적으로 활동하는 JavaScript가 있습니다. 사용자가 사이트를보고 있지 않을 때 (즉, 창이나 탭에 포커스가없는 경우) 실행하지 않는 것이 좋습니다.

JavaScript를 사용하여이를 수행하는 방법이 있습니까?

내 기준점 : 사용중인 창이 활성화되지 않은 경우 Gmail 채팅에서 소리가납니다.


이 답변을 처음 작성한 이후 W3C 덕분에 새로운 사양이 권장 사항 상태에 도달했습니다 . 이제 페이지 가시성 API ( MDN )를 통해 페이지가 사용자에게 숨겨 졌을 때 더 정확하게 감지 할 수 있습니다.

document.addEventListener("visibilitychange", onchange);

현재 브라우저 지원 :

  • Chrome 13 이상
  • Internet Explorer 10 이상
  • Firefox 10 이상
  • Opera 12.10+ [ 노트 읽기 ]

다음 코드는 호환되지 않는 브라우저에서 덜 안정적인 흐림 / 초점 방법으로 대체됩니다.

(function() {
  var hidden = "hidden";

  // Standards:
  if (hidden in document)
    document.addEventListener("visibilitychange", onchange);
  else if ((hidden = "mozHidden") in document)
    document.addEventListener("mozvisibilitychange", onchange);
  else if ((hidden = "webkitHidden") in document)
    document.addEventListener("webkitvisibilitychange", onchange);
  else if ((hidden = "msHidden") in document)
    document.addEventListener("msvisibilitychange", onchange);
  // IE 9 and lower:
  else if ("onfocusin" in document)
    document.onfocusin = document.onfocusout = onchange;
  // All others:
  else
    window.onpageshow = window.onpagehide
    = window.onfocus = window.onblur = onchange;

  function onchange (evt) {
    var v = "visible", h = "hidden",
        evtMap = {
          focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
        };

    evt = evt || window.event;
    if (evt.type in evtMap)
      document.body.className = evtMap[evt.type];
    else
      document.body.className = this[hidden] ? "hidden" : "visible";
  }

  // set the initial state (but only if browser supports the Page Visibility API)
  if( document[hidden] !== undefined )
    onchange({type: document[hidden] ? "blur" : "focus"});
})();

onfocusin하고 onfocusout있다 IE 9에 필요한 낮출 모든 다른 사람을 활용하면서, onfocus그리고 onblur아이폰 OS, 용도를 제외 onpageshow하고 onpagehide.


당신이해야 할 일은 다음과 같기 때문에 jQuery를 사용할 것입니다.

$(window).blur(function(){
  //your code here
});
$(window).focus(function(){
  //your code
});

아니면 적어도 그것은 나를 위해 일했습니다.


사용자가 HTML 페이지를 볼 수 있는지 확인하는 데 사용되는 일반적인 방법은 3 가지가 있지만 완벽하게 작동하는 방법은 없습니다.

  • W3C 페이지 가시성 API는 이 작업을 수행 할 예정이다 (파이어 폭스 10, MSIE (10), 크롬 13부터 지원). 그러나이 API는 브라우저 탭이 완전히 재정의 된 경우 (예 : 사용자가 한 탭에서 다른 탭으로 변경하는 경우)에만 이벤트를 발생시킵니다. 100 % 정확도로 가시성을 결정할 수없는 경우 API는 이벤트를 발생시키지 않습니다 (예 : 다른 응용 프로그램으로 전환하려면 Alt + Tab).

  • 사용 초점 / 흐림 기반의 방법은 당신에게 거짓 양성을 많이 제공합니다. 예를 들어 사용자가 브라우저 창 위에 더 작은 창을 표시하면 브라우저 창에서 포커스 onblur를 잃어 버릴 수 있지만 ( 올림) 사용자는 여전히 볼 수 있으므로 새로 고쳐야합니다. http://javascript.info/tutorial/focus 참조

  • 사용자 활동 (마우스 이동, 클릭, 키 입력) 에 의존 하면 오탐도 많이 발생합니다. 위와 같은 경우 또는 비디오를 보는 사용자를 생각해보십시오.

위에서 설명한 불완전한 동작을 개선하기 위해 W3C Visibility API, 포커스 / 블러 및 사용자 활동 방법을 조합하여 오 탐률을 줄였습니다. 이를 통해 다음 이벤트를 관리 할 수 ​​있습니다.

  • 브라우저 탭을 다른 탭으로 변경 (W3C Page Visibility API 덕분에 100 % 정확도)
  • 다른 창에 의해 잠재적으로 숨겨지는 페이지 (예 : Alt + Tab) (확률 적 = 100 % 정확하지 않음)
  • 잠재적으로 HTML 페이지에 집중되지 않는 사용자주의 (확률 적 = 100 % 정확하지 않음)

이것이 작동 방식입니다. 문서가 포커스를 잃으면 문서에 대한 사용자 활동 (예 : 마우스 이동)이 모니터링되어 창이 표시되는지 여부를 결정합니다. 페이지 가시성 확률은 페이지에서 마지막 사용자 활동 시간에 반비례합니다. 사용자가 문서에서 오랫동안 활동하지 않으면 페이지가 보이지 않을 가능성이 높습니다. 아래 코드는 W3C Page Visibility API를 모방 한 것입니다. 동일한 방식으로 작동하지만 오 탐률이 낮습니다. 다중 브라우저라는 장점이 있습니다 (Firefox 5, Firefox 10, MSIE 9, MSIE 7, Safari 5, Chrome 9에서 테스트 됨).


    <div id = "x"> </ div>

    <스크립트>
    / **
    지정된 개체의 이벤트에 처리기를 등록합니다.
    @param obj 이벤트를 발생시킬 객체
    @param ev 이벤트 유형 입력 : 클릭, 키 누르기, 마우스 오버, ...
    @param fn 이벤트 핸들러 함수
    @param isCapturing 이벤트 모드 설정 (true = 이벤트 캡처, false = 버블 링 이벤트)
    @return 이벤트 핸들러가 올바르게 첨부 된 경우 true
    * /
    function addEvent (obj, evType, fn, isCapturing) {
      if (isCapturing == null) isCapturing = false; 
      if (obj.addEventListener) {
        // Firefox
        obj.addEventListener (evType, fn, isCapturing);
        true를 반환하십시오.
      } else if (obj.attachEvent) {
        // MSIE
        var r = obj.attachEvent ( 'on'+ evType, fn);
        반환 r;
      } else {
        거짓 반환;
      }
    }

    // 잠재적 인 페이지 가시성 변경에 등록
    addEvent (document, "potentialvisilitychange", function (event) {
      document.getElementById ( "x"). innerHTML + = "potentialVisilityChange : potentialHidden ="+ document.potentialHidden + ", document.potentiallyHiddenSince ="+ document.potentiallyHiddenSince + "s <br>";
    });

    // W3C 페이지 가시성 API에 등록
    var hidden = null;
    var visibleChange = null;
    if (typeof document.mozHidden! == "undefined") {
      hidden = "mozHidden";
      visibleChange = "mozvisibilitychange";
    } else if (typeof document.msHidden! == "undefined") {
      hidden = "msHidden";
      visibleChange = "msvisibilitychange";
    } else if (typeof document.webkitHidden! == "undefined") {
      hidden = "webkitHidden";
      visibleChange = "webkitvisibilitychange";
    } else if (typeof document.hidden! == "hidden") {
      hidden = "숨겨 짐";
      visibleChange = "visibilitychange";
    }
    if (hidden! = null && visibilityChange! = null) {
      addEvent (document, visibilityChange, function (event) {
        document.getElementById ( "x"). innerHTML + = visibilityChange + ":"+ hidden + "="+ 문서 [숨김] + "<br>";
      });
    }


    var potentialPageVisibility = {
      pageVisibilityChangeThreshold : 3 * 3600, // 초
      init : function () {
        function setAsNotHidden () {
          var dispatchEventRequired = document.potentialHidden;
          document.potentialHidden = false;
          document.potentiallyHiddenSince = 0;
          if (dispatchEventRequired) dispatchPageVisibilityChangeEvent ();
        }

        function initPotentiallyHiddenDetection () {
          if (! hasFocusLocal) {
            // 창에 포커스가 없습니다 => 창에서 사용자 활동을 확인합니다.
            lastActionDate = 새 날짜 ();
            if (timeoutHandler! = null) {
              clearTimeout (timeoutHandler);
            }
            timeoutHandler = setTimeout (checkPageVisibility, potentialPageVisibility.pageVisibilityChangeThreshold * 1000 + 100); // Firefox에서 반올림 문제를 피하기 위해 + 100ms
          }
        }

        function dispatchPageVisibilityChangeEvent () {
          unifiedVisilityChangeEventDispatchAllowed = false;
          var evt = document.createEvent ( "Event");
          evt.initEvent ( "potentialvisilitychange", true, true);
          document.dispatchEvent (evt);
        }

        function checkPageVisibility () {
          var potentialHiddenDuration = (hasFocusLocal || lastActionDate == null? 0 : Math.floor ((new Date (). getTime ()-lastActionDate.getTime ()) / 1000));
                                        document.potentiallyHiddenSince = potentialHiddenDuration;
          if (potentialHiddenDuration> = potentialPageVisibility.pageVisibilityChangeThreshold &&! document.potentialHidden) {
            // 페이지 가시성 변경 임계 값 증가 => 짝수 높이기
            document.potentialHidden = true;
            dispatchPageVisibilityChangeEvent ();
          }
        }

        var lastActionDate = null;
        var hasFocusLocal = true;
        var hasMouseOver = true;
        document.potentialHidden = false;
        document.potentiallyHiddenSince = 0;
        var timeoutHandler = null;

        addEvent (document, "pageshow", function (event) {
          document.getElementById ( "x"). innerHTML + = "pageshow / doc : <br>";
        });
        addEvent (document, "pagehide", function (event) {
          document.getElementById ( "x"). innerHTML + = "pagehide / doc : <br>";
        });
        addEvent (window, "pageshow", function (event) {
          document.getElementById ( "x"). innerHTML + = "pageshow / win : <br>"; // 페이지가 처음 표시 될 때 발생
        });
        addEvent (window, "pagehide", function (event) {
          document.getElementById ( "x"). innerHTML + = "pagehide / win : <br>"; // 제기되지 않음
        });
        addEvent (document, "mousemove", function (event) {
          lastActionDate = 새 날짜 ();
        });
        addEvent (document, "mouseover", function (event) {
          hasMouseOver = true;
          setAsNotHidden ();
        });
        addEvent (document, "mouseout", function (event) {
          hasMouseOver = false;
          initPotentiallyHiddenDetection ();
        });
        addEvent (window, "blur", function (event) {
          hasFocusLocal = false;
          initPotentiallyHiddenDetection ();
        });
        addEvent (window, "focus", function (event) {
          hasFocusLocal = true;
          setAsNotHidden ();
        });
        setAsNotHidden ();
      }
    }

    potentialPageVisibility.pageVisibilityChangeThreshold = 4; // 테스트에 4 초
    potentialPageVisibility.init ();
    </ script>

현재 오 탐지없이 작동하는 브라우저 간 솔루션이 없으므로 웹 사이트에서주기적인 활동을 비활성화하는 것에 대해 두 번 더 생각해야합니다.


GitHub에서 사용할 수있는 깔끔한 라이브러리가 있습니다.

https://github.com/serkanyersen/ifvisible.js

예:

// If page is visible right now
if( ifvisible.now() ){
  // Display pop-up
  openPopUp();
}

사용중인 모든 브라우저에서 버전 1.0.1을 테스트했으며 다음에서 작동하는지 확인할 수 있습니다.

  • IE9, IE10
  • FF 26.0
  • 크롬 34.0

... 그리고 아마도 모든 최신 버전.

완전히 작동하지 않습니다 :

  • IE8-항상 탭 / 창이 현재 활성 상태임을 나타냅니다 ( .now()항상 true나에게 반환 됨 ).

내 앱에 대한 Comet Chat을 만들고 다른 사용자로부터 메시지를 받으면 다음을 사용합니다.

if(new_message){
    if(!document.hasFocus()){
        audio.play();
        document.title="Have new messages";
    }
    else{
        audio.stop();
        document.title="Application Name";
    } 
}

사용 : 페이지 가시성 API

document.addEventListener( 'visibilitychange' , function() {
    if (document.hidden) {
        console.log('bye');
    } else {
        console.log('well back');
    }
}, false );

사용해도 되나요 ? http://caniuse.com/#feat=pagevisibility


커뮤니티 위키 답변을 사용하기 시작했지만 Chrome에서 alt-tab 이벤트를 감지하지 못한다는 것을 깨달았습니다. 이는 사용 가능한 첫 번째 이벤트 소스를 사용하기 때문이며이 경우 Chrome에서는 alt-tabbing을 추적하지 않는 것으로 보이는 페이지 가시성 API입니다.

페이지 포커스 변경 대해 가능한 모든 이벤트를 추적하기 위해 스크립트를 약간 수정하기로 결정했습니다 . 드롭 할 수있는 함수는 다음과 같습니다.

function onVisibilityChange(callback) {
    var visible = true;

    if (!callback) {
        throw new Error('no callback given');
    }

    function focused() {
        if (!visible) {
            callback(visible = true);
        }
    }

    function unfocused() {
        if (visible) {
            callback(visible = false);
        }
    }

    // Standards:
    if ('hidden' in document) {
        document.addEventListener('visibilitychange',
            function() {(document.hidden ? unfocused : focused)()});
    }
    if ('mozHidden' in document) {
        document.addEventListener('mozvisibilitychange',
            function() {(document.mozHidden ? unfocused : focused)()});
    }
    if ('webkitHidden' in document) {
        document.addEventListener('webkitvisibilitychange',
            function() {(document.webkitHidden ? unfocused : focused)()});
    }
    if ('msHidden' in document) {
        document.addEventListener('msvisibilitychange',
            function() {(document.msHidden ? unfocused : focused)()});
    }
    // IE 9 and lower:
    if ('onfocusin' in document) {
        document.onfocusin = focused;
        document.onfocusout = unfocused;
    }
    // All others:
    window.onpageshow = window.onfocus = focused;
    window.onpagehide = window.onblur = unfocused;
};

다음과 같이 사용하십시오.

onVisibilityChange(function(visible) {
    console.log('the page is now', visible ? 'focused' : 'unfocused');
});

이 버전은 모든 다른 가시성 이벤트를 수신 하고 변경 사항이있는 경우 콜백을 실행합니다. focusedunfocused핸들러는 다수의 API를 같은 가시성 변경을 잡을 경우 콜백이 여러 번 호출하지 않아야합니다.


이것은 정말 까다 롭습니다. 다음 요구 사항을 고려할 때 해결책이없는 것 같습니다.

  • 페이지에 사용자가 제어 할 수없는 iframe이 있습니다.
  • TAB 변경 (ctrl + tab) 또는 창 변경 (alt + tab)에 의해 트리거되는 변경에 관계없이 가시성 상태 변경을 추적하려고합니다.

이것은 다음과 같은 이유로 발생합니다.

  • 페이지 가시성 API는 탭 변경 (iframe 포함)을 안정적으로 알려줄 수 있지만 사용자가 창을 변경할 때 알려줄 수는 없습니다.
  • 창 흐림 / 초점 이벤트를 수신하면 iframe에 포커스가없는 한 alt + tab 및 ctrl + tabs를 감지 할 수 있습니다.

이러한 제한을 감안할 때-페이지 가시성 API-창 흐림 / 초점-document.activeElement를 결합하는 솔루션을 구현할 수 있습니다.

다음을 수행 할 수 있습니다.

  • 1) 상위 페이지에 포커스가있을 때 ctrl + tab : 예
  • 2) iframe에 포커스가있을 때 ctrl + tab : 예
  • 3) 상위 페이지에 포커스가있을 때 alt + tab : 예
  • 4) iframe에 포커스가있을 때 alt + tab : 아니요 <-부끄러움

iframe에 포커스가 있으면 흐림 / 초점 이벤트가 전혀 호출되지 않고 페이지 Visibility API가 alt + tab에서 트리거되지 않습니다.

@AndyE의 솔루션을 기반으로 https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test1.html (죄송합니다. JSFiddle에 문제가 있음) 에서이 (거의 좋은) 솔루션을 구현했습니다 .

Github에서도 사용할 수 있습니다 : https://github.com/qmagico/estante-components

이것은 크롬 / 크롬에서 작동합니다. iframe 콘텐츠를로드하지 않는다는 점을 제외하고는 파이어 폭스에서 작동합니다.

어쨌든 마지막 문제 (4)를 해결하기 위해 할 수있는 유일한 방법은 iframe에서 흐림 / 초점 이벤트를 수신하는 것입니다. iframe을 일부 제어 할 수있는 경우 postMessage API를 사용하여 수행 할 수 있습니다.

https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test2.html

나는 여전히 충분한 브라우저로 이것을 테스트하지 않았습니다. 이것이 작동하지 않는 부분에 대한 자세한 정보를 찾을 수 있으면 아래 의견에 알려주십시오.


var visibilityChange = (function (window) {
    var inView = false;
    return function (fn) {
        window.onfocus = window.onblur = window.onpageshow = window.onpagehide = function (e) {
            if ({focus:1, pageshow:1}[e.type]) {
                if (inView) return;
                fn("visible");
                inView = true;
            } else if (inView) {
                fn("hidden");
                inView = false;
            }
        };
    };
}(this));

visibilityChange(function (state) {
    console.log(state);
});

http://jsfiddle.net/ARTsinn/JTxQY/


이것은 크롬 67, 파이어 폭스 67에서 나를 위해 작동합니다.

if(!document.hasFocus()) {
    // do stuff
}

사용할 수 있습니다 :

(function () {

    var requiredResolution = 10; // ms
    var checkInterval = 1000; // ms
    var tolerance = 20; // percent


    var counter = 0;
    var expected = checkInterval / requiredResolution;
    //console.log('expected:', expected);

    window.setInterval(function () {
        counter++;
    }, requiredResolution);

    window.setInterval(function () {
        var deviation = 100 * Math.abs(1 - counter / expected);
        // console.log('is:', counter, '(off by', deviation , '%)');
        if (deviation > tolerance) {
            console.warn('Timer resolution not sufficient!');
        }
        counter = 0;
    }, checkInterval);

})();

HTML 5에서는 다음을 사용할 수도 있습니다.

  • onpageshow: 창이 보이면 실행할 스크립트
  • onpagehide: 창이 숨겨 졌을 때 실행할 스크립트

보다:


이것은 Andy E의 답변을 수정 한 것입니다.

이렇게하면 30 초마다 페이지를 새로 고치지 만 페이지가 표시되고 초점이 맞춰진 경우에만 작업이 수행됩니다.

가시성이 감지되지 않으면 초점 만 사용됩니다.

사용자가 페이지에 초점을 맞추면 즉시 업데이트됩니다.

페이지는 Ajax 호출 후 30 초까지 다시 업데이트되지 않습니다.

var windowFocused = true;
var timeOut2 = null;

$(function(){
  $.ajaxSetup ({
    cache: false
  });
  $("#content").ajaxComplete(function(event,request, settings){
       set_refresh_page(); // ajax call has just been made, so page doesn't need updating again for 30 seconds
   });
  // check visibility and focus of window, so as not to keep updating unnecessarily
  (function() {
      var hidden, change, vis = {
              hidden: "visibilitychange",
              mozHidden: "mozvisibilitychange",
              webkitHidden: "webkitvisibilitychange",
              msHidden: "msvisibilitychange",
              oHidden: "ovisibilitychange" /* not currently supported */
          };
      for (hidden in vis) {
          if (vis.hasOwnProperty(hidden) && hidden in document) {
              change = vis[hidden];
              break;
          }
      }
      document.body.className="visible";
      if (change){     // this will check the tab visibility instead of window focus
          document.addEventListener(change, onchange,false);
      }

      if(navigator.appName == "Microsoft Internet Explorer")
         window.onfocus = document.onfocusin = document.onfocusout = onchangeFocus
      else
         window.onfocus = window.onblur = onchangeFocus;

      function onchangeFocus(evt){
        evt = evt || window.event;
        if (evt.type == "focus" || evt.type == "focusin"){
          windowFocused=true; 
        }
        else if (evt.type == "blur" || evt.type == "focusout"){
          windowFocused=false;
        }
        if (evt.type == "focus"){
          update_page();  // only update using window.onfocus, because document.onfocusin can trigger on every click
        }

      }

      function onchange () {
        document.body.className = this[hidden] ? "hidden" : "visible";
        update_page();
      }

      function update_page(){
        if(windowFocused&&(document.body.className=="visible")){
          set_refresh_page(1000);
        }
      }


  })();
  set_refresh_page();
})

function get_date_time_string(){
  var d = new Date();
  var dT = [];
  dT.push(d.getDate());
  dT.push(d.getMonth())
  dT.push(d.getFullYear());
  dT.push(d.getHours());
  dT.push(d.getMinutes());
  dT.push(d.getSeconds());
  dT.push(d.getMilliseconds());
  return dT.join('_');
}

function do_refresh_page(){

// do tasks here

// e.g. some ajax call to update part of the page.

// (date time parameter will probably force the server not to cache)

//      $.ajax({
//        type: "POST",
//        url: "someUrl.php",
//        data: "t=" + get_date_time_string()+"&task=update",
//        success: function(html){
//          $('#content').html(html);
//        }
//      });

}

function set_refresh_page(interval){
  interval = typeof interval !== 'undefined' ? interval : 30000; // default time = 30 seconds
  if(timeOut2 != null) clearTimeout(timeOut2);
  timeOut2 = setTimeout(function(){
    if((document.body.className=="visible")&&windowFocused){
      do_refresh_page();
    }
    set_refresh_page();
  }, interval);
}

약간 더 복잡한 방법은 setInterval()마우스 위치를 확인하고 마지막 확인과 비교하는 데 사용 하는 입니다. 마우스가 일정 시간 동안 움직이지 않으면 사용자가 유휴 상태 일 수 있습니다.

이 대신에, 사용자가 유휴 상태 인 경우 이야기의 추가 이점이 바로 윈도우가 활성화되지 않은 경우 검사합니다.

많은 사람들이 지적했듯이 사용자 또는 브라우저 창이 유휴 상태인지 여부를 항상 확인하는 좋은 방법은 아닙니다. 사용자가 마우스를 사용하지 않거나 비디오를 시청 중이거나 이와 유사한 것일 수 있기 때문입니다. 나는 유휴 상태를 확인하는 한 가지 가능한 방법을 제안하고 있습니다.


jQuery가없는 솔루션의 경우 세 가지 페이지 상태에 대한 정보를 제공 하는 Visibility.js확인 하십시오.

visible    ... page is visible
hidden     ... page is not visible
prerender  ... page is being prerendered by the browser

또한 setInterval에 대한 편의 래퍼

/* Perform action every second if visible */
Visibility.every(1000, function () {
    action();
});

/* Perform action every second if visible, every 60 sec if not visible */
Visibility.every(1000, 60*1000, function () {
    action();
});

이전 브라우저 (IE <10, iOS <7)에 대한 대체도 가능합니다.


angular.js의 경우 컨트롤러가 가시성의 변화에 ​​반응 할 수 있도록 허용하는 (허용 된 답변에 기반한) 지시문이 있습니다.

myApp.directive('reactOnWindowFocus', function($parse) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            var hidden = "hidden";
            var currentlyVisible = true;
            var functionOrExpression = $parse(attrs.reactOnWindowFocus);

          // Standards:
          if (hidden in document)
            document.addEventListener("visibilitychange", onchange);
          else if ((hidden = "mozHidden") in document)
            document.addEventListener("mozvisibilitychange", onchange);
          else if ((hidden = "webkitHidden") in document)
            document.addEventListener("webkitvisibilitychange", onchange);
          else if ((hidden = "msHidden") in document)
            document.addEventListener("msvisibilitychange", onchange);
          else if ("onfocusin" in document) {
                // IE 9 and lower:
            document.onfocusin = onshow;
                document.onfocusout = onhide;
          } else {
                // All others:
            window.onpageshow = window.onfocus = onshow;
                window.onpagehide = window.onblur = onhide;
            }

          function onchange (evt) {
                //occurs both on leaving and on returning
                currentlyVisible = !currentlyVisible;
                doSomethingIfAppropriate();
          }

            function onshow(evt) {
                //for older browsers
                currentlyVisible = true;
                doSomethingIfAppropriate();
            }

            function onhide(evt) {
                //for older browsers
                currentlyVisible = false;
                doSomethingIfAppropriate();
            }

            function doSomethingIfAppropriate() {
                if (currentlyVisible) {
                    //trigger angular digest cycle in this scope
                    scope.$apply(function() {
                        functionOrExpression(scope);
                    });
                }
            }
        }
    };

});

다음 예제와 같이 사용할 수 있습니다. <div react-on-window-focus="refresh()">, refresh()은 컨트롤러가 범위에있는 범위의 범위 함수입니다.


전체 브라우저 블러 대해 조치를 취하려는 경우 : 내가 언급했듯이 브라우저가 초점을 잃으면 제안 된 이벤트가 실행되지 않습니다. 내 생각은 루프에서 카운트 업하고 이벤트가 발생하면 카운터를 재설정하는 것입니다. 카운터가 한계에 도달하면 다른 페이지에 대한 location.href를 수행합니다. dev-tools에서 작업하는 경우에도 발생합니다.

var iput=document.getElementById("hiddenInput");
   ,count=1
   ;
function check(){
         count++;
         if(count%2===0){
           iput.focus();
         }
         else{
           iput.blur();
         }
         iput.value=count;  
         if(count>3){
           location.href="http://Nirwana.com";
         }              
         setTimeout(function(){check()},1000);
}   
iput.onblur=function(){count=1}
iput.onfocus=function(){count=1}
check();

이것은 FF에서 성공적으로 테스트 된 초안입니다.

참고 URL : https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active

반응형