I would like to tell whether my browser's tab is in focus, and whether the browser itself is in the foreground or in the background.
Is there a javascript interface that queries the foreground/background status of the browser?
Update Following Palpatim's answer below, I found this practical HTML5Rocks tutorial about the page visibility API.
Your browser support requirements will determine whether this is viable, but the Page Visibility API may get you part of the way there.
It doesn't determine foreground/background status; to my knowledge there is no API available to JavaScript that will give you that level of access, so you'd have to rely on a browser plugin to report it. However, it will report whether a page is visible or not, which for many use cases is all that's required.