Chrome Extension: How to force a script to start only when the previous one is finished?

Asked

Viewed 263 times

1

I have an extnsão that makes the change of colors in the images of the web pages. When the extension is activated (via an icon in Toolbar), the images in all tabs open pages are recolored. When the URL of a tab is updated, the images are then recolored as well. But in order not to show the original page until the images change is complete, I hide the document (through "hide.js"). Then I call "Recolor.js", which changes the images and finally "shows.js" makes the document visible. The problem is that the document is visible before the images are recolored. So, how can I force the "show.js" script to run only after finishing the "Recolor.js" script"?

Here is part of the file where the script files are called.

background js.

chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
 if (flag){
   if (info.status != "complete") 
     chrome.tabs.executeScript(tabid, {file:"esconde.js", runAt: 'document_start' });
   if (info.status == "complete") {
     chrome.tabs.executeScript(tabid, {file:"recolor.js", runAt: 'document_start' });
     chrome.tabs.executeScript(tabid, {file:"mostra.js", runAt: 'document_start' });
     chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
   }
 }
});

1 answer

1

According to the documentation, the method executeScript accepted as third parameter a callback that runs when the script ends. So you can do so:

chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
  if (flag){
    if (info.status != "complete") 
      chrome.tabs.executeScript(tabid, {file:"esconde.js", runAt: 'document_start' });
    if (info.status == "complete") {
      chrome.tabs.executeScript(tabid, {file:"recolor.js", runAt: 'document_start' }, function() {
        chrome.tabs.executeScript(tabid, {file:"mostra.js", runAt: 'document_start' });
      });
      chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
    }
  }
});
  • Thanks for the suggestion, but it still doesn’t work. You can still see the original images first.

  • Then there must be some asynchronous operation occurring in the Recolor.js file. Is there any way to post the contents of that file? If it is large, better put in some external service and post the link.

  • Thank you for the availability. My email is [email protected]. If you want, send me an email, I send the full zipped extension. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.