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.

1
  • First, ask yourself how to stop execute JavaScript in a page? Commented Jun 29, 2011 at 14:34

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Calling document.write() is probably not a great idea, since it will obliterate the page :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.