Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Update tab in Loop Not Working in Chrome Extension Extension


I am trying to build a chrome extension that will loop through some specific URLs in one tab. I am using chrome local storage to store the URLs. Here is the background.js part where I'm trying to do the tab update,

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === 'sending_links_of_posts') {
    changeUrl(request);
  }
});

function changeUrl(request) {
  const urlArr = request.url;
  console.log(urlArr);
  chrome.storage.local.set({ urls: urlArr }, function () {
    console.log('Urls stored. \n' + urlArr);
  });
  chrome.storage.local.get(['urls'], function (result) {
    for (let i = 1; i < result.urls.length; i++) {
      console.log('Value currently is ' + result.urls[i]);
      chrome.tabs.update(undefined, {
        url: 'https://m.facebook.com' + urlArr[i],
      });
    }
  });
}

Chrome only opens the first link tab it gets. I've tabs and storage permission in my manifest.json. I've tried chrome.tabs.create, and that creates new tabs for all the URLs. But I need to update the current tab only. I am using the manifest_version: 2. What am I missing here?


Solution

  • Someone from a discord channel helped me find the answer. The function I want to implement can be achieved using this code.

    let i;
    
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.message === 'sending_links_of_posts') {
        // initialize index
        i = 0;
        // add urls to local storage
        const urlArr = request.url;
        console.log(urlArr);
        chrome.storage.local.set({ urls: urlArr }, function () {
          console.log('Urls stored. \n' + urlArr);
        });
        // start changing the url
        changeUrl(i);
      }
    });
    
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
      // only update after the page has loaded
      if(changeInfo.status === "complete") {
        i++;
        changeUrl(i);
      }
    });
    
    function changeUrl(i) {
      chrome.storage.local.get(['urls'], function (result) {
          if (i >= result.urls.length) {
            return;
          }
          console.log('Value currently is ' + result.urls[i]);
          chrome.tabs.update(undefined, {
            url: 'https://m.facebook.com/' + result.urls[i],
          });
    
      });
    }
    

    Wrapping the changeUrl function into a setTimeout or implementing a sleep function can help to slow the URL changing process.