简体   繁体   中英

Is it possible to detect when a user switches to a different browser tab?

I'm trying to detect when a user switches away from the current browser tab, to another tab. Listening for window.onblur works well in firefox for detecting when the user switches focus to another window, but it doesn't seem to fire when the user switches to another tab. However, it seems that onfocus is fired when switching to the tab in question, from another tab.

Is there a way to detect when the user switches away from the current tab?

显然在Firefox中,如果你使用document.onBlur而不是window.onblur作为事件处理程序,它将适用于制表符切换。

This example code seemed to work for me. I edited the code to display an alert box when I switched tab (please dont do it). It resulted in a infinite loop ;-) and had to close FF using task manager.

Source : http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

function onBlur() {
    document.body.className = 'blurred';
};
function onFocus(){
    document.body.className = 'focused';
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM