我希望能够检测用户是否正在使用广告拦截软件,当他们访问我的网站。如果他们正在使用它,我想显示一条消息,要求他们关闭它以支持项目,就像这个网站一样。

如果你进入该网站,而你的浏览器启用了某种广告拦截软件,那么该网站就不会显示真正的广告,而是显示一个小横幅,告诉用户广告收入用于托管项目,他们应该考虑关闭广告拦截。

我想在我的网站上做到这一点,我正在使用adsense广告,我怎么能做到呢?


当前回答

这为我工作,文件必须准备好之前,你寻找广告块 希望这能帮助到一些人!

jQuery(document).ready(function() {

var adBlockEnabled = false;
var testAd = document.createElement('div');
testAd.innerHTML = ' ';
testAd.className = 'adsbox';
document.body.appendChild(testAd);
window.setTimeout(function() {
  if (testAd.offsetHeight === 0) {
    adBlockEnabled = true;
  }
  testAd.remove();
  console.log('AdBlock Enabled? ', adBlockEnabled)
}, 100);


});

其他回答

不是一个直接的回答,但我会把信息放在广告后面。而不是试图检测它,它会在广告没有显示时显示出来。

我有点晚了,这里有一个最简单的解决方案,我知道的老AdSense代码与jQuery:

$ads = $("ins");
if ($ads.length == 0) {
    // Replacement code about you needing ad income
}

在纯JavaScript中:

$ads = document.getElementsByTagName("ins");
if ($ads.length == 0) {
    // Replacement code about you needing ad income
}

对于$ads,您可以使用任何与正在生成的广告一致的选择器。例如,对于新的AdSense代码,您可以使用$("iframe#google_ads_frame1")。

async function hasAdBlock() {
  try {
    await fetch("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
      method: "HEAD",
      mode: "no-cors",
    })
    return false;
  } catch(e) {
    return true;
  }
}

你可以看看这个,可能会有帮助 detect-adblocker

它是一个定时答案的实现

将此添加到head标签中的任何脚本之前:

<head>
    <title></title>
    <meta/>

    <!--adBlocker detection code - START-->
    <script src="//adblocker.fortiapp.com/ads.js"></script>
    <script>
        (function (i, o, g, r) {
            i[o] = (typeof i[o] == typeof undefined) ? g : r
        })(window, 'adblocker', true, false);
    </script>
    <!--adBlocker detection code - END-->

    // Other scripts

</head>

然后再使用它:

if (adblocker) {
    // the add blocker is enabled
}else{
    // ad blocker is not enabled
}

你不需要一个额外的HTTP请求,你可以简单地计算一个假添加的高度。

顺便说一下,这里有一个完整的列表,与广告拦截器避免渲染的元素相匹配。

窗口。adBlockRunning = function() { return (getComputedStyle(document.getElementById("detect"))["display"] == "none") ?真:假; }() console.log (window.adBlockRunning); #{检测 身高:1 px; 宽度:1 px; 位置:绝对的; 左:-999 em; 上图:-999年新兴市场 } <div id="detect" class="ads AD adsbox doubleclick AD -placement carbon-ads"></div>