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

1

I have an extension that makes the colors change in the images of web pages. When the extension is activated (through an icon in the toolbar), the images on all pages opened in the tabs are recolored. When the URL of a tab is updated, the images are then recolored as well. But, so as not to show the original page until the image changes, I hide the document (through "hides.js"). Then I call "recolor.js", which makes changes to the images and , finally "show.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 I finish the "recolor.js" script?

Here is part of the file where 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});
   }
 }
});
    
asked by anonymous 04.05.2014 / 22:53

1 answer

1

According to documentation , the executeScript method accepts as a third parameter a callback that runs when the script finishes. So you can do this:

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});
    }
  }
});
    
05.05.2014 / 05:43