This extension runs a command when the window or the editor change focus. You can specify the command and whether to run the command when the editor doesn't change (i.e., not run it when you change windows back and forth).
Written so that I can quit the insert mode in vim when I switch to another window, so for now it will not run the command if you have something selected in the editor. In the future I plan to make this a setting as well.