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

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

javascript - Determine whether webpage has foreground window focus/is active tab?

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

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...