繁体   English   中英

chrome扩展代码以获取当前的活动标签页网址,并检测其中的所有网址更新

[英]chrome extension code to get current active tab url and detect any url update in it as well

我想写一个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,并且只有在我们在选项卡之间切换并返回此选项卡时才会这样做。 我想检测两种情况。 我应该如何更改我的代码?

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

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

您应该使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM