PDA

View Full Version : How do I get this function to work in IE?



christianbarkholt
05-29-2015, 11:41 PM
Hi there,

I'm trying to make a javaScript function that can alter a piece of HTML code based on whether an ad-blocker is detected.

I want to to modify the top margin of an iframe. To do so, I need to execute a function ( writeiframe() ) inside another function that is inside setTimeout(). This works well in Chrome, but for some reason I can't get it to work in IE.

I have posted the main javaScript code below. This is a link to the full code: http://kulsvierhytten.dk/iframe-adblock.html

I'm not quite used to dealing with javaScript, so any and all help will be greatly appreciated. :)


function detect()
{
//create a iframe. Append the iframe to the body. And then after 100ms check if their offsetHeight, display or visibility is set such a way that user cannot see them.
//In the URL use the words specific to advertising so that Adblock can do string matching.
var iframe = document.createElement("iframe");
iframe.height = "1px";
iframe.width = "1px";
iframe.id = "ads-text-iframe";
iframe.src = "http://domain.com/ads.html";

document.body.appendChild(iframe);

setTimeout(function()
{
var iframe = document.getElementById("ads-text-iframe");
if(iframe.style.display == "none" || iframe.style.display == "hidden" || iframe.style.visibility == "hidden" || iframe.offsetHeight == 0)
{
adBlock = "margin-top: -174px;";
alert(adBlock);
iframe.remove();
writeiframe();
}
else
{
adBlock = "margin-top: 0px;";
alert(adBlock);
iframe.remove();
writeiframe();
}
}, 100);
}
detect();

coothead
05-30-2015, 02:33 AM
Hi there christianbarkholt,


and a warm welcome to these forums. ;)

Your problem is caused by the use of "remove()".

Further reading:-


http://red-team-design.com/removing-an-element-with-plain-javascript-remove-method/

Instead of...


iframe.remove();
...it would be safer to use...


document.body.removeChild(iframe);

Also note that you really should not be using "document.write()"
here either.

But if you must insist on using it, then you should, at least, include
"document.close()" at the end of each statement.

This will stop the page from hanging,



coothead

christianbarkholt
05-30-2015, 12:13 PM
Wow. Thanks a lot coothead! :D

I changed iframe.remove() and added document.close(), and it works perfectly.

And thanks for the warm welcome too.

In terms of document.write(): I know it's not really the way to do it. I made the original script a while ago, and will change it when I get some extra time on my hands. :)

coothead
05-30-2015, 12:31 PM
No problem, you're very welcome. ;)


coothead