检测网页是否使用adblock

经常看到有网站提示“我们检测到你可能使用了 AdBlock 或 Adblock Plus,它的部分策略可能会影响到正常功能的使用”,希望用户将该站点添加到adblock白名单,那么我们应该用什么手段检测网页是否适用AdBlock呢?

一般来说,AdBlock 的工作机制是它会维护一个规则列表,如果页面中的元素命中了某个规则,则就会将其屏蔽。我们创建一个ads.js文件,并写入:

1
isAdBlockActive = false;

这样,如果 AdBlock 成功运行,isAdBlockActive 变量就会是 undefined,然后我们再添加一段 js 代码检测其状态,或给出提出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var AdBlocker = (function () {

function showModal() {
$('#modal_ad_blocker').modal(); // show a message to the user when ads are blocked
}

setInterval(function () {
// Get the first AdSense ad unit on the page
var ad = document.querySelector("ins.adsbygoogle");

// If the ads.js or the Google ads are not loaded, show modal and track the event
if (typeof isAdBlockActive === 'undefined'
|| (ad && ad.innerHTML.replace(/\s/g, "").length === 0)) {

showModal();

if (typeof ga !== 'undefined') {
// Log an event in Universal Analytics
// but without affecting overall bounce rate
ga('send', 'event', 'Adblock', 'Yes', {'nonInteraction': 1});

} else if (typeof _gaq !== 'undefined') {
// Log a non-interactive event in old Google Analytics
_gaq.push(['_trackEvent', 'Adblock', 'Yes', undefined, undefined, true]);
}
}
}, 5000); // check every 5 seconds

})();

将上述文件和代码写入一个 test.html 文件中,访问该文件并切换 AdBlock 状态来查看运行效果。据此就可以判断出当前用户是否适用屏蔽插件了!