如何为每个标签保留chrome.browserAction.setBadgeText?

时间:2022-08-26 21:32:15

My extension gets data using tab.url and puts it in chrome.browserAction.setBadgeText. When i open a new tab it resets. How can i update BadgeText only for a new tab? and keep it unchanged for an old one?

我的扩展使用tab.url获取数据并将其放在chrome.browserAction.setBadgeText中。当我打开一个新标签时,它会重置。如何仅为新标签更新BadgeText?为旧的保持不变?

extension layout:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
function(tabId, changeInfo, tab){
    //using tab.url and XMLHttpRequest() i get newText for:
    chrome.browserAction.setBadgeText({text: newText});
   };
});

2 个解决方案

#1


7  

Two key points should help you with your troubles.

两个关键点应该可以帮助您解决问题。

1) chrome.browserAction.setBadgeText has an optional parameter, tabId, that binds the value to the tab.

1)chrome.browserAction.setBadgeText有一个可选参数tabId,它将值绑定到选项卡。

2) You should filter chrome.tabs.onUpdated events by changeInfo's fields.

2)您应该通过changeInfo的字段过滤chrome.tabs.onUpdated事件。

So, change your code to:

因此,将您的代码更改为:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    function(tabId, changeInfo, tab){
        if(!changeInfo.url) return; // URL did not change
        // Might be better to analyze the URL to exclude things like anchor changes

        /* ... */
        chrome.browserAction.setBadgeText({text: newText, tabId: tab.id});
    };
});

This might not catch new tabs' creation; if it doesn't, also listen to onCreated

这可能无法捕捉新标签的创建;如果没有,也听取onCreated

#2


2  

 chrome.browserAction.setBadgeText({text: newText}, tab.id);  //<<this is not working to me

 chrome.browserAction.setBadgeText({text: "Phish", tabId: tab.id}); //<<This is working to me

#1


7  

Two key points should help you with your troubles.

两个关键点应该可以帮助您解决问题。

1) chrome.browserAction.setBadgeText has an optional parameter, tabId, that binds the value to the tab.

1)chrome.browserAction.setBadgeText有一个可选参数tabId,它将值绑定到选项卡。

2) You should filter chrome.tabs.onUpdated events by changeInfo's fields.

2)您应该通过changeInfo的字段过滤chrome.tabs.onUpdated事件。

So, change your code to:

因此,将您的代码更改为:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    function(tabId, changeInfo, tab){
        if(!changeInfo.url) return; // URL did not change
        // Might be better to analyze the URL to exclude things like anchor changes

        /* ... */
        chrome.browserAction.setBadgeText({text: newText, tabId: tab.id});
    };
});

This might not catch new tabs' creation; if it doesn't, also listen to onCreated

这可能无法捕捉新标签的创建;如果没有,也听取onCreated

#2


2  

 chrome.browserAction.setBadgeText({text: newText}, tab.id);  //<<this is not working to me

 chrome.browserAction.setBadgeText({text: "Phish", tabId: tab.id}); //<<This is working to me