【问题标题】:chrome extension code to get current active tab url and detect any url update in it as wellchrome 扩展代码来获取当前活动的标签 url 并检测其中的任何 url 更新
【发布时间】:2019-02-22 06:51:39
【问题描述】:

我想编写一个 chrome 扩展程序,它可以获取活动选项卡的 URL。我希望它始终在当前活动窗口的活动选项卡上显示该人正在查看的当前网站。我在后台脚本中使用以下代码:

chrome.tabs.onActivated.addListener( function(activeInfo){
    chrome.tabs.get(activeInfo.tabId, function(tab){
        y = tab.url;
        console.log("you are here: "+y);
    });
});

每当我更改浏览器中的活动选项卡时,此代码都会很好地显示当前网址。但是,如果我通过单击或键入手动更改活动选项卡 url,它将无法注册新 url,并且只有在我们在选项卡之间切换并返回此选项卡时才会这样做。我想检测这两种情况。我应该如何更改我的代码?

【问题讨论】:

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


    【解决方案1】:

    下面是处理这两种情况的脚本:

    chrome.tabs.onActivated.addListener( function(activeInfo){
        chrome.tabs.get(activeInfo.tabId, function(tab){
            y = tab.url;
            console.log("you are here: "+y);
        });
    });
    
    chrome.tabs.onUpdated.addListener((tabId, change, tab) => {
        if (tab.active && change.url) {
            console.log("you are here: "+change.url);           
        }
    });
    

    【讨论】:

      【解决方案2】:

      你应该使用chrome.tabs.onUpdated.addListener api

      const getActiveUrl = (tabid, changeInfo, tab) => {
        const url = changeInfo.url;
      
        // url is likely to be empty, and filter chrome:// and about:// URLs
        if (!url || ['chrome://', 'about://'].some(p => url.startsWith(p))) return;
      
        // filtering is not an active tab
        if (!tab.active) return;
      
        // the url address you need
        console.log(url);
      }
      
      chrome.tabs.onUpdated.addListener(getActiveUrl);
      
      

      【讨论】:

      • 不应该是if (!tab.active) return;吗?
      • 是的,我没有注意到这个错误,非常感谢您的纠正,我已经解决了这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多