In this blog post, we will learn how to add AdBlocker detection to your Hugo blog using the PaperMod theme. We will also include a simple warning message for users who have an ad-blocker enabled, encouraging them to disable it or whitelist your website.

Overview

Here’s a quick overview of the steps we will take:

  1. Create a custom CSS file to style the warning message.
  2. Create a JavaScript file to detect ad-blockers.
  3. Add a partial HTML file for the warning message.
  4. Extend the head and footer partials to include our new files.

Step-by-step Guide

1. Create a custom CSS file

Create a new file named custom_css.css under the assets/css/extended/ directory and paste the following CSS code:

#adblock-warning {
  background-color: #f2dede;
  color: #a94442;
  border-color: #ebccd1;
  padding: 15px;
  margin-bottom: 20px;
  border: 1px solid transparent;
  border-radius: 4px;
}

2. Create a JavaScript file to detect ad-blockers

Create a new file named adblock-detection.js under the static/js/ directory and paste the following JavaScript code:

function detectAdBlocker() {
  const adBlockTest = document.createElement('div');
  adBlockTest.innerHTML = ' ';
  adBlockTest.className = 'ad ads adbadge doubleclick BannerAd adsbox ad-placeholder ad-placement';
  document.body.appendChild(adBlockTest);
  window.setTimeout(() => {
    if (adBlockTest.offsetHeight === 0) {
      document.getElementById('adblock-warning').style.display = 'block';
      console.log('Ad-blocker detected.');
    } else {
      console.log('No ad-blocker detected.');
    }
    adBlockTest.remove();
  }, 100);
}

window.addEventListener('load', detectAdBlocker);

3. Add a partial HTML file for the warning message

Create a new file named adblock-warning.html under the layouts/partials/ directory and paste the following HTML code:

<div id="adblock-warning" style="display:none;">
  <p>Please consider disabling your ad-blocker or whitelisting our website. Ads help support our content and keep it free for everyone. Thank you!</p>
</div>

Edit the layouts/partials/extend_head.html file and add the following line:

<link rel="stylesheet" href="{{ "css/extended/custom_css.css" | relURL }}">

Edit the layouts/partials/extend_footer.html file and add the following line:

<script src="{{ "js/adblock-detection.js" | relURL }}" defer></script>

Conclusion

With the above steps completed, you have successfully added AdBlocker detection to your Hugo blog using the PaperMod theme. Visitors with an ad-blocker enabled will now see a polite warning message encouraging them to disable it or whitelist your website, helping to support your content and keep it free for everyone.


Source code : https://github.com/hobbyworker/hugo-demo

Demo : https://hobbyworker.me/hugo-demo