Search code examples
crossriderbrowser-addons

Change browser add-on icon and data, according to active tab


Currently, I have a crossrider add on consisting of an extension.js and a background.js

In the extension.js, I send a GET request to the page which the user is currently on. In this GET request, I am collecting some data.

I am storing the domain name (protocol + domain) in a local Crossrider Database, and for every get request, I am making sure that the domain being requested is not present in the database, and if it is found in the database, I am preventing the request from occurring (for optimisation purposes).

Now, the problem is that I want it so that every time the user changes their tab, the browser add-on icon and data presented (e.g. browserAction Icon Label) to the user is changed respective to the domain they are currently on, within that tab.

For example:

Tab 1 - https://www.google.com Tab 2 - https://www.yahoo.com

When a user is on Tab 1, the browser add-on icon and details change respectively to that URL. As soon as he/she switches to Tab 2, the details are changed again respective to the URL they are on. If a user visits a new website in the same tab, the details of the browser add-on, should again be respective to the new URL they have visited.

Thanks very much


Solution

  • My understanding of your requirements, as you nicely described them, are comprised of 2 components that can be addressed in the background scope using the following Crossrider methods:

    1. To detect tab changes use appAPI.tabs.onTabSelectionChanged.
    2. To monitor URL changes use appAPI.webRequest.onBeforeNavigate

    To simplify the code, I would use a common function for the button updates. So for example, in the background.js file your code would look like:

    appAPI.ready(function($) {
        // Monitor tab selection changes
        appAPI.tabs.onTabSelectionChanged(function(tabInfo) {
            // tabInfo.Id = Tab Id
            // tabInfo.tabUrl = URL in tab
            updateButton(tabInfo.tabUrl);
        });
    
        appAPI.webRequest.onBeforeNavigate.addListener(function(details, opaqueData) {
            // details.pageUrl = URL of the tab requesting the page
            // opaqueData = data passed to the context of the callback function
            updateButton(details.pageUrl);
        });
    
        function updateButton(url) {
            // Your code to update the button based on URL
        }
    });

    [Disclosure: I am a Crossrider employee]