This snippet of code, will detect how many tabs are open and how many are active (visible) and if none of tabs is active, it will choose last opened tab, as active one This code will handle on windows/tab crash too.
source: https://jsfiddle.net/rezaamya/7kq9uL0x/3/