user3059287
user3059287

Reputation: 56

Chrome extension: Run before load (rendering) a page

I have a Google Chrome Extension working, which objective is to change the color of the pixel images, in the web pages.

To change the color of the images in web pages, from the tabs already open I use the code (in the background.js file):

function executeScriptsInExistingTabs(){
  chrome.windows.getAll(null, function(wins) {
    for (var j = 0; j < wins.length; ++j) {
      chrome.tabs.getAllInWindow(wins[j].id, function(tabs) {
        for (var i = 0; i < tabs.length; ++i) {
          if (tabs[i].url.indexOf("chrome://") != 0) {
            chrome.tabs.executeScript(tabs[i].id, { file: 'muda_conteudo.js' });
            chrome.browserAction.setIcon({path: "on.png", tabId:tabs[i].id});
          }
        }
      });
     }
   });
 }

To change the color in the web pages, when the URL of the tab is changed, I use the following code (in the background.js file):

chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
  if (flag){
    if (info.status == "complete") {
       chrome.tabs.executeScript(tabid, {file:"muda_conteudo.js"});
       chrome.browserAction.setIcon({path: "on.png", tabId:tab.id})
    }
  }
});

I works perfectly. But, when I open the new tab, I see the original images and, I see the recolored images, only a few microseconds later. I would like to improve this, seeing the page only after the recoloring (I don't want to see the original).

Anyone has idea about how to solve it ? Thanks in advance.

Upvotes: 2

Views: 4257

Answers (1)

Pawel Uchida-Psztyc
Pawel Uchida-Psztyc

Reputation: 3838

It's all about the line:

info.status == "complete"

It means that Chrome will execute your script after page load - which include assets loading like images. You have two options here.

First one (easy one) is to load second script before loaded event is fired and hide e.g. body until second script execute (of course you can combine both scripts into one and wait for dom load event to do the rest of work).

Second one is more complicated. Because first method is not recommended from UX point of view (hiding content until some event fire) you can use more advanced event handling. You can insert code into the page when it start loading, listen for mutation events on body elements and check for DOMNodeInserted event. Then you can check if new node is an image (exactly one you looking for) and then replace it. Then you shouldn't see old images. Additionally you can set elements visibility state to invisible until new image is loaded.

Hope it will help you.

Upvotes: 5

Related Questions