【问题标题】:Detect which tab/window is being focused in Google Chrome检测 Google Chrome 中的焦点是哪个选项卡/窗口
【发布时间】:2011-08-29 03:56:36
【问题描述】:

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

  • 内容脚本被注入到每个页面中
  • 每 5 秒定期调用函数“a”
  • 如果页面处于焦点位置,则调用函数“b”。

理想情况下,应该为每个选项卡调用函数“a”,但函数“b”只会为焦点所在的选项卡调用。

我已经研究了几种方法,我找到的最接近的解决方案是: How to detect when a tab is focused or not in Chrome with Javascript?

但是,当我尝试使用 outerHeight/innerHeight 方法时,它给了我一些非常奇怪的结果。当窗口失焦时,outerHeight 为 0。这对我来说更像是一个错误,所以我不确定是否可以使用它来确定选项卡是否失焦。

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

【问题讨论】:

    标签: javascript html google-chrome google-chrome-extension


    【解决方案1】:

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

    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
                }
            });
        }
    });
    

    【讨论】:

    • 太棒了。比 document.hasFocus() 更可靠
    猜你喜欢
    • 1970-01-01
    • 2023-02-26
    • 2013-02-18
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多