如何检测广告拦截器

发布于:2021-01-23 00:00:28

0

888

0

拦截器 Ad Blocker JavaScript

互联网的潜规则之一是大多数内容都是“免费的”……代价是网页上到处都是广告和追踪器。在早期的互联网时代,这并不是一个大问题,但追踪器和广告已经变得如此具有侵入性和不可原谅的侵犯性,以至于你几乎需要使用一个广告拦截浏览器扩展。

广告拦截器非常流行,像Brave这样的浏览器吹嘘自己围绕着广告拦截展开。我经常去一个网站,看到一个模态,我禁用了我的广告拦截器,这让我思考最好的方法来检测广告拦截器。经过各种测试和实验,我发现了一个非常简单的方法来检测广告拦截器!

本质上,我的方法试图加载谷歌的广告服务JavaScript文件,如果请求失败,这可能是由于用户有一个广告拦截器:

// Determines if the user is likely using an ad block extension
async function checkAdBlocker() {
 // Used to cache the result
 let isBlocked;

 async function tryRequest() {
   try {
     return fetch(
       new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
         method: 'HEAD',
         mode: 'no-cors'
       }))
       .then(function(response) {
         // Google Ads request succeeded, so likely no ad blocker
         isBlocked = false;
         return isBlocked;
       }).catch(function(e) {
         // Request failed, likely due to ad blocker
         isBlocked = true;
         return isBlocked;
       });
   } catch (error) {
     // fetch API error; possible fetch not supported (old browser)
     // Marking as a blocker since there was an error and so
     // we can prevent continued requests when this function is run
     console.log(error);
     isBlocked = true;
     return isBlocked;
   }
 }

 return isBlocked !== undefined ? isBlocked : await tryRequest();
}

// Using the ad block checker
const usingBlocker = await checkAdBlocker();

这背后的逻辑如下:

谷歌的广告文件,adsbygoogle.js是一个完美的示例文件,因为它被认为是头号敌人——由于谷歌的广告服务受欢迎,广告拦截器想要拦截的第一个文件

该文件也是至关重要的谷歌的业务,因此99.999999999%的正常运行时间几乎得到了保证

几乎不可能出现网络问题;误报可能来自网络连接问题或坏的服务工作者

如果你不认为adsbygoogle.js是最好的示例文件,你可以很容易地将它切换到其他URL

从内容创建者的角度来看,一个导航属性可以让你知道是否使用了广告拦截器是最理想的……但这不会很快发生(…没有,真的)。然而,使用这样简单的代码片段,可以为用户启用广告拦截器提供一个合理的提示!