Site icon T4Tutorials.com

Code for wp site to detect if someone is blocking ads on my site, and ask them to unblock ads

Steps to Add This to Your WordPress Site:

  1. Add the JavaScript Code to your theme’s header.php or enqueue it in your functions.php.
  2. Create a CSS-styled message to inform users about ad blocking.

JavaScript Code:

<script>
document.addEventListener("DOMContentLoaded", function () {
    // Create a hidden div that adblockers usually block
    let adDiv = document.createElement("div");
    adDiv.className = "adsbygoogle";
    adDiv.style.display = "none";
    document.body.appendChild(adDiv);

    // Check if the element is being blocked
    setTimeout(() => {
        if (adDiv.offsetHeight === 0) {
            showAdBlockMessage();
        }
    }, 500);

    function showAdBlockMessage() {
        let messageBox = document.createElement("div");
        messageBox.innerHTML = `
            <div id="adblock-message" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
            background: white; padding: 20px; border: 2px solid red; text-align: center; z-index: 10000;">
                <h3>We've detected you're using an Ad Blocker</h3>
                <p>Please consider disabling it to support our website.</p>
                <button onclick="document.getElementById('adblock-message').remove()">Close</button>
            </div>`;
        document.body.appendChild(messageBox);
    }
});
</script>
Exit mobile version