最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to detect when a user switches to a different browser tab? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Aug 3, 2009 at 5:27 Scotty AllenScotty Allen 13.5k9 gold badges40 silver badges51 bronze badges 1
  • Update: As of 2013 all major browsers provide support for the so-called visiblity API. See here for a sample: stackoverflow./a/19519701/603003 – ComFreek Commented Oct 23, 2013 at 14:07
Add a ment  | 

2 Answers 2

Reset to default 8

Apparently in Firefox it'll work for tab switching if you use document.onBlur instead of window.onblur for the event handler.

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./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;
}
发布评论

评论列表(0)

  1. 暂无评论