3

Is it possible in javascript to only execute javascript if the user is on the actual tab/page?

Like if he switches to another tab then the javascript process will be paused and when he returns to the tab the javascript will continue the process.

Tomkay
  • 5,120
  • 21
  • 60
  • 92

1 Answers1

6

There is no direct way unless you use browser-specific code, or code that's not completely standard (see katspaugh's answer).

'Stop' solution

  • design your code so that it is "stoppable". That's something you have to figure out for your context.

  • Then add something like below:

..

<html> 
<head> 
</head> 
<body> 
    <script> 
    window.onblur = function() {
        yourStopFunctionHere().
    }
    </script> 

</body> 
</html> 

'Assert' solution

Insert the following code where it really matters that the window has focus:

if(windowHasFocus()) {
    //your code here
}

There are different methods for testing if window has focus: JavaScript / jQuery: Test if window has focus

Asyncronous solution

whenWindowHasFocus(fn); //where fn is the function you want to only run when window has focus

One of two possible implementations exist.....

Waiting via setTimeout

function WhenWindowHasFocus(yourFunction){
    if(windowHasFocus()) {
        yourFunction();
    }
    setTimeout(function(){ WhenWindowHasFocus(yourFunction); }, 1000);
}

Waiting via custom events

Or even better, if you can wrap the window-focused-dependent functionality (the functionality dependent on the window having focus) into a separate function, then "hook" that function to window.onfocus. Be careful with this one though. You don't wan't to completely overwrite the window.onfocus function (or you undo the previous work you just did). Instead, you may have to use custom events of some sort. Most js frameworks provide custom events. If you go this route, the window.onfocus function will simply trigger some custom event, and you don't have to manually writing any looping code with setTimeout.

//The below is pseudo-code. custom events differ between js frameworks

window.onfocus = function(){
    window.FocusEvent.trigger()
}

function WhenWindowHasFocus(yourFunction){
    if(windowHasFocus()) {
        yourFunction();
    }
    window.focusEvent.addOnlyOnce(yourFunction);
}
Community
  • 1
  • 1
Alexander Bird
  • 38,679
  • 42
  • 124
  • 159
  • 1
    Calling `document.write()` is probably not a great idea, since it will obliterate the page :-) – Pointy Jun 29 '11 at 14:43