When switching tabs through the chrome extension, how to store the title of the respective tabs in an array

Viewed 33

I want to collect and store tab titles through chrome extension. Therefore, even when switching tabs, it is necessary to store the title array of the first tab and other tabs and finally return the title of the first tab. The function I am currently using as follows. But when the tab is changed, the title of the first tab us replaced by second (changed) title. How to store the relevant title in an array? Can it be done only through a content script?

contentScript.js

    var pageTitleRegxArray = ["li[class*=selected][class*=tab]", 
    "li[class*=active][class*=tab]", "li[class*=Selected][class*=menu]", 
    "li[class*=selected][class*=menu]", "li[class*=active][class*=menu]", 
    "span[class*=title]","span[class*=Title]"];
    
    
    function getPageInfor() {
        var titles = [];
        for (var i = 0; i < pageTitleRegxArray.length; i++) {
            var title = document.querySelectorAll('' + pageTitleRegxArray[i] + '');
            if (title[0]) {
                var currentTitle = title[0].innerText || title[0].textContent;
                currentTitle = currentTitle.trim();
                if(currentTitle){
                  titles.push(currentTitle);
                }
            }
        }
        if (titles.length == 0) {
           titles.push(document.title);
        }
        return titles;
    }
1 Answers

You can use chrome.tabs and chrome.runtime.sendMessage API. You can send a message from content script to background script and get the tabs' title in response.

content-script.js:

chrome.runtime.sendMessage({action: get_tab_title}, function(response){
 if(response.titles){
  var titles = response.titles;
 }
});

backgorund-script.js:

chrome.runtime.onMessage.addListener(function(request, sender) {
 if(request.action == "get_tab_title"){
  var titles = [];
  chrome.tabs.query({}, function(tabs){    // gets all tabs
   for(var i = 0; i < tabs.length; i++){
    titles.push(tabs[0].title);
   }
   sendResponse({titles: titles});
  }
  return 1; //returning 1 because we are sending response async-ly (refer documentaion)
 }
});

So, mostly you would have to split your getPageInfor() function or handle by returning promise.

Related