firefoxfirefox-addonfirefox-addon-sdkhistoryfirefox-addon-webextensions

How to get the current tab's history in a Web Extension in Firefox?


Is there an API that makes it possible to get the current tab's history in a Web Extension in Firefox? Just like when clicking and holding on the Back button, a dropdown will appear to show the current tab's history.


Solution

  • No. You cannot ask for the list for a certain tab by default.

    You can, however, listen for the tab events onUpdated, onCreated etc. Using the tabId which stays the same, you can keep a list of URLs in a background script (background.js) which is always running if the addon is enabled.

    You would do it like this:

    let arr=[]; // At the top of background.js
    browser.tabs.onCreated.addListener(handleCreated); // Somewhere in background.js
    
    function handleCreated(tab) {
      let tabId = tab.id;
      if(arr[tabId]==null) arr[tabId] = [];
      arr[tabId].push(url);
    }
    
    function getHistoryForCurrentTab(){
      function currentTabs(tabs) {
        // browser.tabs.query returns an array, lets assume the first one
        // (it's safe to assume)
        let tab = tabs[0];
        // tab.url requires the `tabs` permission (manifest.json)
        // We will now log the tab history to the console.
        for(let url of arr[tab.id]){
          console.log(url);
        }
      }
    
      function onError(error) {
        console.log(`This should not happen: ${error}`);
      }
    
      browser.tabs.query({currentWindow: true, active: true})
             .then(currentTabs, onError);
    }
    

    The above code is a proof of concept. Some improvements you will need to consider: implement onClosed which resets the tab history for that id (arr[tabId] = null), implement onUpdated (will be needed for sure, same logic as in handleCreated).

    Links: