1

I have an angular js function which should be called for every 2 seconds only when the current tab is open in the browser. Is there any way to check whether the current page is active in the browser.

  $scope.callAtInterval = function() {

      var url = "http://127.0.0.1/test";

        $http.get(url).success( function(response) {
           $scope.initial = response;

        },
         function errorCallback(response) {
          $scope.result=response;
                      });
}

$interval( function(){ $scope.callAtInterval(); }, 5000);

}

Akhil Reddy
  • 23
  • 1
  • 10
  • post your code !! – Sachila Ranawaka Apr 21 '17 at 05:09
  • @sachila ranawaka I posted the code. Here for every 5 seconds the api call will be made and data will be updated. But i want to do tis only when the current tab is active in the browser. – Akhil Reddy Apr 21 '17 at 05:15
  • show the html code also – Sachila Ranawaka Apr 21 '17 at 05:18
  • 1
    Possible duplicate of [Check if a specific tab page is selected (active)](http://stackoverflow.com/questions/8653036/check-if-a-specific-tab-page-is-selected-active) – Hampus Apr 21 '17 at 05:18
  • Possible duplicate of [Is there a way to detect if a browser window is not currently active?](http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) – SAMUEL Apr 21 '17 at 05:22

2 Answers2

2

I think below piece of code is self-explanatory

import { HostListener} from "@angular/core";

  @HostListener("window:visibilitychange", ["$event"])
    onVisibilityChange($event) {
        const isVisible = $event.target.visibilityState === 'visible';
        this.logger.info(isVisible);
        if (isVisible) {
            // tab is visible
        } else {
           // tab is not-visible
        }
    }
Aklesh Singh
  • 917
  • 10
  • 12
0

You would use the focus and blur events of the window:

$(window).on("blur focus", function(e) {
    var prevType = $(this).data("prevType");

    if (prevType != e.type) {   //  reduce double fire issues
        switch (e.type) {
            case "blur":
                // cancel your interval function
                break;
            case "focus":
                // emit your interval function
                break;
        }
    }

    $(this).data("prevType", e.type);
})
Jason
  • 16
  • 2