开发者

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

开发者 https://www.devze.com 2023-03-12 03:40 出处:网络
Using chrome content scripts I want to remove several iframes in a webpage before their content is loaded.

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 manif开发者_开发技巧est 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?


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.


The manifest.json for this should contain content_scripts like:

"content_scripts": [
    {   
        "matches": ["*://*/*"], 
        "js": [ "scan.js" ],
        "run_at": "document_start",
        "all_frames" : true
    }
]
0

精彩评论

暂无评论...
验证码 换一张
取 消