检测/拦截< img>的插入进入DOM [英] Detecting/intercepting insertion of <img> into DOM

查看:74
本文介绍了检测/拦截< img>的插入进入DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用由该分析公司提供的第三方分析报告脚本。它将一个1x1像素的图像添加到DOM中,并在图像的URL中报告数据。

We're using a third-party analytics reporting script provided by this analytics company. It adds a 1x1 pixel image into the DOM with reporting data in the URL of the image.

有没有办法让我监视DOM并拦截这个< img> 元素,并在浏览器请求图像之前更改其src属性?

Is there any way for me to monitor the DOM and intercept this <img> element and change its "src" attribute before the browser requests the image?

听起来像一个非常奇怪的事情我知道,但是有一个我们想要侵入这个报告脚本的功能(这个脚本被弄脏了)。

Sounds like a really odd thing to do, I know, but there's a feature we'd like to hack onto this reporting script (the script is obsfucated).

推荐答案

p>在非IE浏览器中,您可以使用 DOMNodeInserted 事件来检测DOM节点的插入。我不知道浏览器是否会在触发事件的时候发出HTTP请求;似乎没有在Firefox中进行快速测试。因为这在IE中不起作用,所以这可能不是一个可以接受的解决方案。

In non-IE browsers, you can detect the insertion of a DOM node by using the DOMNodeInserted event. I don't know if the browser will have made the HTTP request by the time the event is fired; it appears not to in Firefox from a quick test. Since this doesn't work in IE, this may not be an acceptable solution anyway.

document.body.addEventListener("DOMNodeInserted", function(evt) {
    var node = evt.target;
    if (node.nodeType == 1 && node.tagName == "IMG") {
        node.src = "http://www.gravatar.com/avatar/be21766f09e0e5fd3a2f8cc721ceba2e?s=32&d=identicon&r=PG"; // Your gravatar
    }
}, false);

这篇关于检测/拦截&lt; img&gt;的插入进入DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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