在处理DOM之前,如何使用Google Chrome内容脚本修改网页? [英] How can I modify a web page using google chrome content script before the DOM is processed?

查看:159
本文介绍了在处理DOM之前,如何使用Google Chrome内容脚本修改网页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用chrome内容脚本我想在加载内容之前删除网页中的多个iframe。

我发现,在扩展清单中使用属性run_at:document_start后,我的javascript就在主页面请求之后,处理DOM之前执行,图像,iframe等被加载。 Logicaly在这一点上的DOM结构不availabel,我不能修改该页面使用类似命令:

  myelement = document.getElementById ( 'iframeX'); 

myelement.parentNode.removeChild(myelement);

如何访问和修改需要的页面数据?


<您需要在document_start上触发您的内容脚本并添加一个beforeload监听器 - 您可以使用event.preventDefault选择性地阻止加载内容,然后删除尝试过的框架加载内容:

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

博客介绍了使用Firefox的beforeload事件的等效方法


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?

解决方案

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.

这篇关于在处理DOM之前,如何使用Google Chrome内容脚本修改网页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆