Reputation: 45
I'm using Javascript to implement some kind of instant messaging. When a message arrives, I want to play a sound if the user is not focused on the browser window and no sound otherwise. I've seen about window.onfocus and window.onblur but these seem to be event listeners. Instead, I want something simpler which will return me true or false in a sequential code; so that
if (windowOpen) // user on my window
{
playSound();
}
// do rest of the messaging
Is there such a simple, preferably single-line technique?
Upvotes: 0
Views: 3100
Reputation: 4273
I think there isn't any single-line technique for this.
See: http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
Upvotes: 1
Reputation:
I don't understand what you have against event listeners, or why it needs to be on a single line. Seems like listeners are exactly what you need, irrespective of how many lines.
var focused = true;
window.onfocus = window.onblur = function(e) {
focused = (e || event).type === "focus";
}
function yourMessagingFunc() {
if (focused === false) {
playSound();
}
}
Upvotes: 3