admin管理员组

文章数量:1410730

I'm making a Chrome extension that contains a content script that does the following:

  • the content script is injected into every page
  • periodically calls function "a" every 5 seconds
  • if the page is in focus, it calls function "b".

Ideally, function "a" should be called for every tab, but function "b" will only be called for the tab that is focused.

I've looked into several ways of doing this, the closest solution I've found is this: How to detect when a tab is focused or not in Chrome with Javascript?

However, when I tried to use the outerHeight/innerHeight method, it gave me some really weird results. When the window is out of focus, I get 0 for outerHeight. Which seems more like a bug to me, so I'm not sure if I can use this to determine whether the tab is out of focus or not.

Does anyone have a good solution for this?

I'm making a Chrome extension that contains a content script that does the following:

  • the content script is injected into every page
  • periodically calls function "a" every 5 seconds
  • if the page is in focus, it calls function "b".

Ideally, function "a" should be called for every tab, but function "b" will only be called for the tab that is focused.

I've looked into several ways of doing this, the closest solution I've found is this: How to detect when a tab is focused or not in Chrome with Javascript?

However, when I tried to use the outerHeight/innerHeight method, it gave me some really weird results. When the window is out of focus, I get 0 for outerHeight. Which seems more like a bug to me, so I'm not sure if I can use this to determine whether the tab is out of focus or not.

Does anyone have a good solution for this?

Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked May 19, 2011 at 19:28 Tony StarkTony Stark 3,4637 gold badges28 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Don't know a content script only solution, but this can be easily done with help of background page:

content_script.js:

function task() {
    chrome.extension.sendRequest("is_selected", function(isSelected) {
        if(isSelected) {
            //this tab in focus
        } else {
            //not in focus
        }
    });
}
setInterval(task, 5000);

background.html:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request == "is_selected") {
        chrome.tabs.getSelected(null, function(tab){
            if(tab.id == sender.tab.id) {
                sendResponse(true); //in focus (selected)
            } else {
                sendResponse(false);    //not in focus
            }
        });
    }
});

本文标签: javascriptDetect which tabwindow is being focused in Google ChromeStack Overflow