Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026
The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.
It’s pretty common for prosumers 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 to run it 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 if it’s dark mode, makes it a link, and adds it to the page.