David Hinojosa
David Hinojosa

Reputation: 219

How to display my own images when user uses AdBlock?

I found this snippet of code and it works well to display the same content on each adsense ad unit. However, since my knowledge of scripting is limited, I don't know how to make it so that I can display my own images for each different ad size. I need to be able to display my own image for each 728x90, and 160x600, ad units.

<script>
window.onload = function(){
  setTimeout(showAdblockImage, 3000); 
};
function showAdblockImage(){
    //get all google ad elements
    var adsList = document.querySelectorAll("ins.adsbygoogle");
    if(!adsList){ return;}
    for(var i=0; i<adsList.length;i++){
        if(adsList[i].innerHTML.replace(/\s/g, "").length != 0){
            //AdBlock is not active, hence exit
            break;
        }
        //apply inline css to force display
        adsList[i].style.cssText = 'display:block !important';
        //modify html content of element
        adsList[i].innerHTML='AD BLOCK USED';
    } 
}
</script> 

Upvotes: 0

Views: 137

Answers (2)

David Hinojosa
David Hinojosa

Reputation: 219

I figured it out thanks to Advocat's comment. Here's the final code. I needed to add if statements to select only 1 ad, and then replace that ad with my own code.

Here's what is working for me:

<script>
window.onload = function(){
  setTimeout(showAdblockImage, 0000); 
};
function showAdblockImage(){
    //get all google ad elements
    var adsList = document.querySelectorAll("ins.adsbygoogle");
    if(!adsList){ return;}
    for(var i=0; i<adsList.length;i++){
        if(adsList[i].innerHTML.replace(/\s/g, "").length != 0){
            //AdBlock is not active, hence exit
            break;
        }
        //apply inline css to force display
        adsList[i].style.cssText = 'display:block !important';

    // select ad # 1
    if (i==0){
        adsList[i].innerHTML='<a href="#"><img src="image1.png"></a>';
}
   // select ad #2
    if (i==1){
        adsList[i].innerHTML='<a href="#"><img src="image-2.png"></a>';
}

    } 

}
</script>

Upvotes: 0

user8579087
user8579087

Reputation:

Your code selects each element ins.adsbygoogle and replaces it with the text "AD BLOCK USED".

To replace the ad with an image instead, try to use adsList[i].innerHTML="<a href='#'><img src='photo.png'></a>"; instead of adsList[i].innerHTML="AD BLOCK USED";

Upvotes: 1

Related Questions