Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
It’s pretty common for power users and technical people like programmers to use an adblocker.
One thing I wanted to do was to promote one of my products only if you had an adblocker enabled, so you don’t see an ad from Carbon, the network I use, but a link to something I do want to promote.
This JavaScript snippet helps detect adblockers:
let adBlockEnabled = false
const ad = document.createElement('div')
ad.innerHTML = ' '
ad.className = 'adsbox'
document.body.appendChild(ad)
window.setTimeout(function() {
if (ad.offsetHeight === 0) {
adBlockEnabled = true
}
ad.remove()
console.log('Blocking ads? ', adBlockEnabled)
}
}, 100)
Make sure you place it at the bottom of the page so it runs when the DOM is loaded, or wait for the DOMContentLoaded event.
Once you know the adBlockEnabled value, you can add your own custom ad to the page.
Here’s a script to display a custom promotion:
if (adBlockEnabled) {
const link = document.createElement('a')
link.setAttribute('href', 'https://flaviocopes.com')
link.setAttribute('target', '_blank')
const img = document.createElement('img')
img.src = '/img/image.png'
img.style.paddingBottom = '30px'
img.style.margin = '0 auto'
img.style.maxWidth = '65%'
if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
img.style.filter = 'invert(100%)'
}
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (e) => {
const newColorScheme = e.matches ? 'dark' : 'light'
if (newColorScheme === 'light') {
img.style.filter = ''
} else {
img.style.filter = 'invert(100%)'
}
})
link.appendChild(img)
document.querySelector('.promotion').classList.remove('hidden')
document.querySelector('.promotion').appendChild(link)
}
This loads an image, inverts it in dark mode, makes it a link, and adds it to the page.