Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I've recently added Banggood banner links to my Blog and noticed that Facebook started to use images of those banners whenever I shared a post that didn't have its own image. This was of course an undesirable behaviour and I looked into various ways of removing it and finally settled on a simple JavaScript approach.

When using the Facebook Debugger this is the kind of summary that I was getting...
fbshareimg_remove3.png


The ad image is clearly part of the thumbnail of my shared post. I looked into different ways to fix this and there were a few - I could have used a nested iframe with the ad page loaded inside it, this would require me to generate a whole new HTML page for each banner. I could have also loaded the image using CSS instead of leaving it as an img tag - this required me to change my banner code significantly. These didn't sit well with me so I looked at yet another option which was to use some JavaScript, jQuery in my case, to set the content of a div element that held the ad - this required no change to my banner code.

I already had a div element to hold the ad, all I needed to do was give it an ID, like so:
 HTML
<div id="banggood_banner" class="banggood_banner"></div>


Notice this is an empty div. This is where my Blog's template engine (Smarty) would typically inject ad code, I removed that injection. The template still needed the ad code however, but it was going to be used differently now.

At the bottom of my page (after jQuery scripts were loaded) I added the following bit of code that set the innerHTML value for the div element I've defined above, by calling the html() function...
 JavaScript
<script>
$('#banggood_banner').html('{$ad_code_html}');
</script>




The actual ad content was held in the $ad_code_html template variable, if you want to do this for any other image, just place the literal img tag here instead. Since the Facebook scraper doesn't run JavaScript, it will always see an empty div and not the image content that has been injected into it! In a web browser however the bit of JavaScript will ensure the image/ad is loaded and displayed.

The debugger confirms this change works...
fbshareimg_remove4.png


-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.