Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'd like to be able to mute activity of my app if I can detect that the page is no longer focused. For instance, if the page is in a background tab or another app has focus, I'd like to disable a constantly polling script or switch modal notifications to the new HTML5 notifications API.

Is there any way to get this with JS, and if so, which browsers are supported?

PS - I've seen this, but don't know if it would work for what I'm looking to do. Anybody have any insight?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can listen for the blur event on your window, then for when the user comes back, you can use the focus event:

Here's an example in jQuery:

$(window).blur(disableStuff).focus(enableStuff);

Or in pure JavaScript:

window.onblur = disableStuff;
window.onfocus = enableStuff;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...