How does macOS route keyboard events? I'm mainly wondering about the media keys, but I think that the general question is interesting as well. I have an extension in Chrome that allows me to use the media keys on Youtube, Soundcloud and lots of other sites, I have Spotify installed, and off course, I have iTunes. It doesn't seem predictable what will happen when I press the "play" key, so in cases where it's not based on focus, how does OSX route keyboard events?
I'm not sure how OS X decides which app to send the command. It might have to do with launch order, or last visited order. What I know is that it's decided by rcd: Remote Control Daemon.

When a media key is pressed, Launch Daemon matches the LaunchEvents to com.apple.rcdevent.matching and calls up rcd. Then it just sort of hangs out in the background. You can see it in Activity Monitor. You can kill it and it wouldn't respawn. It just comes back when you press a media key again. The app itself is stored here:

/System/Library/CoreServices/rcd.app


It's launch daemon is here:

/System/Library/LaunchAgents/com.apple.rcd.plist