Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to stop the running of a Javascript web application when the focus is on other window

Are there any way to stop the running of a Javascript web application when the focus is on other window? For example, If I have AJAX executions in a application web, It'd very efficient stop the running in that situation.

like image 404
vicenrele Avatar asked Sep 20 '25 10:09

vicenrele


2 Answers

Using the Page Visibility API

The Page Visibility API performs a simple but important function – it lets your application know when a page is visible to the user. This basic piece of information enables the creation of Web pages that behave differently when they are not being viewed.

Visibility.js - a wrapper for the Page Visibility API

like image 82
CD.. Avatar answered Sep 23 '25 00:09

CD..


Your question is too theoretical. There's no native way in JS for keeping track of window focus, but it's relatively simple to implement your own.

Once you know if the window has focus at a given point in time, you can use this information in your implementation that continuously fires AJAX requests (most likely in some kind of loop) and skip the firing of the request when window is not focused.

E.g.

var winFocused = false;

window.onfocus = function() {
  winFocused = true;
}
window.onblur = function() {
  winFocused = false;
}

Then in your "loop" or whatever, for e.g.:

setInterval(function() {
  if( ! winFocused) return;

  // Otherwise, if winFocused is true, do what you need...

}, 1000);
like image 39
marekful Avatar answered Sep 22 '25 23:09

marekful