5

I feel like this will probably be immediately obvious to any of the non-amateurs out there, but I've been stumped on this for days.

I am writing a Chrome Extension that executes a script at document start. I want to rewrite the HTML of specific DIVs as they load, but before they are displayed to the user (so the user doesn't see the site's HTML before it is unceremoniously replaced by my custom HTML). The method I am trying to use looks like this.

addEventListener('DOMNodeInserted', function(event){
    if(event.relatedNode.innerHTML.indexOf("contentArea")>-1){
        writeContentArea();
    }
}, false);

function writeContentArea(){

    var divtowrite = document.getElementById('contentArea');
    include(divtowrite,"contentArea.html"); //my AJAX include function

}

Now, the problem is, when the page loads and the JS executes, the div will still load before it is replaced. The weird thing is when I try this with a different div, like a sidebar, it works as expected; i.e., the div is replaced before it is displayed to the user. I can't figure out why it works for some divs and not for others.

I don't know if this is relevant, but on the Chrome side I have:

chrome.tabs.getSelected(null, function(tab) {

    if(tab.url.indexOf("search.php") > -1){
        chrome.tabs.executeScript(null,
            {file: "fhrun.js", allFrames: false, runAt: "document_start"}
        );
    }

});

Any ideas of why this isn't working, or a better method that I should be using? Thanks!!

Brian Mayer
  • 989
  • 3
  • 13
  • 23

1 Answers1

0

Not sure if this is the approach you are looking for, but have you considered injecting CSS to hide the content area on initial load and setting it to visible in javascript once you modified the content?

The CSS file would read like this:

#contentArea { display:none; } 

or

#contentArea { visibility:hidden; }

and you would inject it using:

    chrome.tabs.insertCSS(null, 
{file: "youfile.css", allFrames: false, runAt: "document_start"});

Then modify your content changing function to be:

function writeContentArea(){
    var divtowrite = document.getElementById('contentArea');
    include(divtowrite,"contentArea.html"); //my AJAX include function
    divtowrite.style.display = 'block';
}
teddybeard
  • 1,964
  • 1
  • 12
  • 14
  • Thanks, it's a good workaround, but doesn't exactly solve the problem, which is that I want to be able to intercept DOM elements and rewrite them. I also tried using jquery.livequery(); but it had the same problem as DOMNodeInserted. – Brian Mayer Nov 07 '12 at 23:21