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.
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).
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);
Give this a go. I don't know how useful it will be, but I felt like tinkering and it somewhat accounts for the scenario whereby the third party purposefully incorporates a delay:
$(document).ready(function() {
// match an image with specific dimension, return it
function imgNinja() {
var $img = $("img").filter(function() {
return ($(this).height() == 1 && $(this).width() == 1);
});
return $img;
}
// periodically execute this to check for matches
function keepSeeking() {
$img = imgNinja();
if($img.length) {
alert('found it');
clearInterval(i);
// do something with image
}
}
// insert a fake into the DOM at a bit of an interval
function addNastyImage() {
var $invader = $('<img src="foo.jpg" height="1px" width="1px"/>');
$('html').append($invader);
}
setTimeout(addNastyImage, 5000);
var i = setInterval(keepSeeking, 1000);
});
Demo: http://jsfiddle.net/NyEdE/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With