Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检测Google Chrome中关注的选项卡/窗口_Javascript_Html_Google Chrome_Google Chrome Extension - Fatal编程技术网

Javascript 检测Google Chrome中关注的选项卡/窗口

Javascript 检测Google Chrome中关注的选项卡/窗口,javascript,html,google-chrome,google-chrome-extension,Javascript,Html,Google Chrome,Google Chrome Extension,我正在制作一个Chrome扩展,其中包含一个内容脚本,可以执行以下操作: 内容脚本被注入到每个页面中 每隔5秒定期调用函数“a” 如果页面处于焦点位置,则调用函数“b” 理想情况下,应该为每个选项卡调用函数“a”,但函数“b”将仅为聚焦的选项卡调用 我研究了几种方法,找到的最接近的解决方案是: 然而,当我尝试使用outerHeight/innerHeight方法时,它给了我一些非常奇怪的结果。当窗口失焦时,我得到0表示外光。这对我来说更像是一个bug,所以我不确定是否可以用它来确定标签是否

我正在制作一个Chrome扩展,其中包含一个内容脚本,可以执行以下操作:

  • 内容脚本被注入到每个页面中
  • 每隔5秒定期调用函数“a”
  • 如果页面处于焦点位置,则调用函数“b”
理想情况下,应该为每个选项卡调用函数“a”,但函数“b”将仅为聚焦的选项卡调用

我研究了几种方法,找到的最接近的解决方案是:

然而,当我尝试使用outerHeight/innerHeight方法时,它给了我一些非常奇怪的结果。当窗口失焦时,我得到0表示外光。这对我来说更像是一个bug,所以我不确定是否可以用它来确定标签是否不对焦


有人对此有好的解决方案吗?

不知道只使用内容脚本的解决方案,但这可以在后台页面的帮助下轻松完成:

content\u script.js:

function task() {
    chrome.extension.sendRequest("is_selected", function(isSelected) {
        if(isSelected) {
            //this tab in focus
        } else {
            //not in focus
        }
    });
}
setInterval(task, 5000);
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
            }
        });
    }
});
background.html:

function task() {
    chrome.extension.sendRequest("is_selected", function(isSelected) {
        if(isSelected) {
            //this tab in focus
        } else {
            //not in focus
        }
    });
}
setInterval(task, 5000);
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
            }
        });
    }
});

明亮的比document.hasFocus()更可靠