How do I tell which app stole my focus in OS X?

The active window on my machine occasionally loses focus. The active app remains the same -- if I was in Chrome before, I'm still in Chrome now -- but the active window is no longer active. No window is active. This is frustrating; it happened while typing this question, and my keystrokes suddenly stopped registering.

I believe that some other app is stealing focus, but that it itself has no UI to display, so the active window becomes not active, but the active app remains active.

The question is: How do I track down the offending app, so that I can angrily delete it? Normally in cases of focus theft, the culprit is obvious, because it has focus. In this case, I'm stumped.


Here's a script that will tell you which app is activating without telling you. I adapted it from an answer to @KevinReid's question over on Apple SE.

Leave it running in a terminal, wait for the rogue app to steal focus, and see which app is listed last. (For me: Google Drive. Others have reported Symantec AV stuff.)

#!/usr/bin/python                                                                                                       

try:
    from AppKit import NSWorkspace
except ImportError:
    print("Can't import AppKit -- maybe you're running python from brew?")
    print("Try running with Apple's /usr/bin/python instead.")
    exit(1)

from datetime import datetime
from time import sleep

last_active_name = None
while True:
    active_app = NSWorkspace.sharedWorkspace().activeApplication()
    if active_app['NSApplicationName'] != last_active_name:
        last_active_name = active_app['NSApplicationName']
        print('%s: %s [%s]' % (
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            active_app['NSApplicationName'],
            active_app['NSApplicationPath']
        ))
    sleep(1)

This will sound silly and absurdly simple... I had the same problem with my laptop when I used the trackpad or built in keyboard. Had two separate laptops give similar experiences after being exposed to a bit of moisture (yes, I spilled on the keyboard).

Adding peripheral mouse and keyboard resolved it for me.