Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I modify a web page using google chrome content script before the DOM is processed?

Using chrome content scripts I want to remove several iframes in a webpage before their content is loaded.

I found, that using the property run_at:document_start in the extentions manifest my javascript is executed just after the main page request and before the DOM is processed and images, iframes etc. are loaded. Logicaly at this point the DOM structure is not availabel and I can not modify the page using commands like:

myelement=document.getElementById('iframeX');

myelement.parentNode.removeChild(myelement);

How can i access and modify the reqeusted page data then?

like image 712
Cornelius Avatar asked Jun 10 '11 09:06

Cornelius


2 Answers

You need to trigger your content script on document_start and add a beforeload listener - you can use event.preventDefault to selectively block content from loading and then remove the frame that tried to load the content:

    document.addEventListener('beforeload', function(event) {
        if (event.url.match('facebook')) {
            event.preventDefault();
            $(event.target).remove();
        }
    }, false);

I've blogged about an equivalent approach to using the beforeload event for Firefox also.

like image 198
Amir Nathoo Avatar answered Sep 29 '22 17:09

Amir Nathoo


The manifest.json for this should contain content_scripts like:

"content_scripts": [
    {   
        "matches": ["*://*/*"], 
        "js": [ "scan.js" ],
        "run_at": "document_start",
        "all_frames" : true
    }
]
like image 43
kͩeͣmͮpͥ ͩ Avatar answered Sep 29 '22 17:09

kͩeͣmͮpͥ ͩ