My Javascript uses a timer to refresh the CSS of a page. I like to have it run when Safari is in the background and I’m making changes in my code editor, but I don’t want it to run when it’s not in the active browser tab.
window.blur and window.focus get triggered when another tab is in focus, but they also get triggered when the tab is active and Safari is in the background, so they don’t help me here.
How do I detect solely if the tab my Javascript is running in is currently active?
The W3C has a working draft for tracking this exact situation: the page visibility API. It looks like Chrome is the only browser that supports it, currently with an experimental API. You can try it out with this little function in the Web Inspector console:
After playing around with it, I think this is exactly what I need. Basically document.webkitHidden is only false if the document is in the active tab of its window, regardless of whether other windows or applications are active.