I’m trying to run ads on my Next.js 14 site. They work fine on initial load, but the ads disappear when I navigate to a second page. I tried solutions from following sources, but none of them worked for me.
NextJS: Reloading Ads Javascript and Ad Slots on Route Change
Get AdSense Ads to Reload on Route Change in Next JS
here is my code, the script did reloaded on route change, but the ad slot did shown.
declare const window: any
export default function ExoclickSticker(): JSX.Element {
const route = useRouter()
useEffect(() => {
console.log('waiting route change')
if (route) {
console.log('route changed')
const elements = document.getElementsByClassName('XXXXXXX')
for (const element of elements) {
console.log('removing element')
element.remove()
}
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = 'https://a.magsrv.com/ad-provider.js'
script.async = true
script.onload = () => {
console.log('script loaded')
window.AdProvider = window.AdProvider || []
window.AdProvider.push({ serve: {} })
}
document.body.appendChild(script)
const ins1 = document.createElement('ins')
ins1.className = 'XXXXXXX'
ins1.setAttribute('data-zoneid', 'XXXXX')
document.getElementById('exoclick-sticker')?.appendChild(ins1)
return () => {
document.body.removeChild(script)
// document.body.removeChild(ins1)
}
}
}, [route])
return (
<div id="exoclick-sticker">
</div>
)
}