Selcuk pointed me this question, so in order to have this answered here for future search.
The library that would allow to set a global-desktop listener to focus changes is libatspi (the client-side library of GNOME accessibility framework). You could use directly C, pyatspi2 (python manual bindings) or gobject-introspection based bindings (ie, javascript). So a small javascript program that prints name:role_name of the focused object each time the focus change would be:
const Atspi = imports.gi.Atspi;
function onChanged (event) {
log(event.source.get_name() + ',' + event.source.get_role_name());
}
Atspi.init();
let atspiListener = Atspi.EventListener.new(onChanged);
atspiListener.register("object:state-changed:focused");
Atspi.event_main();
In any case, for code examples, you could take a look to recently added focus/caret tracking feature on gnome-shell magnifier (small-size example using javascript) or Orca (GNOME screen reader, big-size example, uses pyatspi2).
libatspi reference here: libatspi Reference Manual
gnome-shell magnifier code here