LoginSignup
0
4

広告ブロックを検出する

Last updated at Posted at 2023-04-17

試しに実装してみた。
コメントの通り。

try {
    const url = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?_=' + Date.now();
    const result = await fetch(url, { // Google Ads にリクエストを投げられるかを調査する。キャッシュされては困るので、no-store も指定しているところしつこいようだけど、クエリパラメータを付けて毎回違うリクエストを投げるようにする
        cache: 'no-store', // キャッシュがある場合それを取得されては困るので、必ずリクエストを投げるようにする
        redirect: 'error' // adsbygoogle.js へのリクエストをリダイレクトするような広告ブロックを検出するため。リダイレクトが発生した場合エラーにする(以下の catch ブロックが実行される)
    });

    // https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-fetch
    if (result.type !== 'cors' || result.url !== url || result.body == null || result.redirected || result.status !== 200) {
        // 広告ブロックがある場合この処理が実行される
    }
} catch (_) { // リダイレクトされたり、単に通信がブロックされたりした場合にこの処理に来る
    // 広告ブロックがある場合この処理が実行される
}

async/await 使わない場合

try {
    const url = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?_=' + Date.now();
    fetch(url, { // Google Ads にリクエストを投げられるかを調査する。キャッシュされては困るので、no-store も指定しているところしつこいようだけど、クエリパラメータを付けて毎回違うリクエストを投げるようにする
        cache: 'no-store', // キャッシュがある場合それを取得されては困るので、必ずリクエストを投げるようにする
        redirect: 'error' // adsbygoogle.js へのリクエストをリダイレクトするような広告ブロックを検出するため。リダイレクトが発生した場合エラーにする(以下の catch ブロックが実行される)
    }).then(result => {
        if (result.type !== 'cors' || result.url !== url || result.body == null || result.redirected || result.status !== 200) {
            // 広告ブロックがある場合この処理が実行される
        }
    }).catch (_ => { // リダイレクトされたり、単に通信がブロックされたりした場合にこの処理に来る
        // 広告ブロックがある場合この処理が実行される
    });
} catch (_) {
    // 広告ブロックがある場合この処理が実行される
}
0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4