Tabbed browsing
Most of the browser support Tabbed browsing so modern browsers have provided a way to detect if tab has focus or switched, HTML 5 provides Page Visibility API
to do this.
Simple script to deal with most of the modern browser like Firefox, Google chrome etc.
var vis = (function(){ var stateKey, eventKey, keys = { hidden: "visibilitychange", webkitHidden: "webkitvisibilitychange", mozHidden: "mozvisibilitychange", msHidden: "msvisibilitychange" }; for (stateKey in keys) { if (stateKey in document) { eventKey = keys[stateKey]; break; } } return function(c) { if (c) document.addEventListener(eventKey, c); return !document[stateKey]; } })();
how to call the function
</pre> vis(function(){ document.title = vis() ? 'Active' : 'Not Active'; }); <pre>
You can check the title to verify that given script is working or not. The title of the page changes accordingly.
Tab browsing
Conclusion
You can use this to to stop video when user looses the focus. You can also use this script to calculate the number second that user spend in your website.