View Full Version : Intercept <img> and <iframe> tag loads

04-29-2012, 03:41 PM

I need to block certain image and iframe content requests to third party urls, based on a condition. Is there a way by which I can intercept the element loads to prevent the HTTP requests being sent?

04-29-2012, 04:22 PM
is this your webpage? or are you asking from a user's perspective?

don't write the offending <img> or <iframe> elements to the page.
If something prevents you from doing this, please explain your situation in more detail.

most modern browsers can be configured to block content from specific domains (to block the iframe you'd probably need to block the domain it serves).
Check your browser's documentation.

I'm sorry; I missed the "based on a condition" part of your post.

If you want to decide whether or not to have an image/iframe, simply leave it out to start, and then write it to the document (or not) via javascript:
var show_iFrame = /* true or false based on whatever condition */;

if( show_iFrame ){
var iFrame = document.createElement( 'iframe' );
var iFrame_src = document.createAttribute( 'src' );
iFrame_src.nodeValue = 'http://custom-anything.com';
iFrame.setAttributeNode( iFrame_src );
var body = document.getElementsByTagName( 'body' )[0];
body.appendChild( iFrame );

I'm "not that great" with javascript, but the above works (though it could probably be done better).

04-30-2012, 09:38 AM

The <img> and <iframe> tags are present in my website, but there are N number of them, so it is practically difficult to modify each of them. What I am trying to achieve is to write a central script that will be included in the head of each of these pages (All of them share a common header). I am trying to intercept the element loads from this script.

04-30-2012, 01:55 PM
I don't know that that approach would work (not sure it's actually possible). Maybe give all the elements in question display: none;, and then JavaScript could try to rewrite the page on the fly...

It would be much more difficult, in any case. I would seriously consider taking the time to rewrite the HTML.

05-01-2012, 03:16 PM
I would consider minimising the number of iframes first of all. Use SSI includes, PHP includes or ASP.NET Master Pages for templates and menus etc.

Then use the iframe's onload event, or HTML5's onready event to capture the iframe's source. Remember to grab the iframe.contentWindow.location.href rather than the iframe.src.