You might want to check the auto-answer package. It works on functions whose the underlying prompt is yes-or-no-p, read-string, read-from-minibuffer, read-key-sequence, read-key-sequence-vector, read-event , read-passwd or lastly read-multiple-choice.
It's pretty easy to use. Just bind auto-answer to a list of (REGEXP ANSWER):
;; Example usage:
;; (let ((...
The short answer is that Emacs running in a terminal cannot observe GUI events such as switching to another tab. If you want Emacs to observe GUI events, run a GUI Emacs.
(This may be possible using a companion program, but even so this would depend to some extent on the goodwill of iTerm2. If it's at all possible, it's not easy and
may have side effects in ...