How to detect Adblock plguin?
如何偵測有否安裝 AdBlock 插件。
參考文章
關鍵知識
All block lists include a reference to "kampyle.js" because it's a common name for JavaScript files that are associated with serving ads.
依 AD Blocker 實作的共同規則都會把這個kampyle.js
檔案阻擋在外,利用這個特性實作偵測是否有安裝啟動 AD Blocker。
開發環境
IDE: Visual Studio 2022 執行平台: .NET6 系統骨架: Blazor Server App
源碼紀錄
在網站根目錄加入 kampyle.js
檔並填入下面程式碼。
// for: detect ad blockers
var e = document.createElement('div');
e.id = 'AntiAdblock-dwZxflhAIjQK';
e.style.display = 'none';
document.body.appendChild(e);
若 Ad Blocker 有啟動則kampyle.js
會被阻檔無法載入,故找不到#AntiAdblock-dwZxflhAIjQK
元素,故有偵測到AdBlocker,反之則反。
@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace YourProject.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="zh-hant">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>YourProject</title>
<base href="~/" />
<link href="YourProject.styles.css" rel="stylesheet" />
@* for: detect ad blockers *@
<style>
#AntiAdblock-nZqKGXDfpEMl {
display: none;
position: fixed;
z-index: 9999;
top: 0;
width: 100%;
padding: 40px 10px;
background: #D30000;
text-align: center;
font-weight: bold;
color: #fff;
}
#AntiAdblock-nZqKGXDfpEMl .dismiss {
cursor: pointer;
color: inherit;
}
</style>
</head>
<body>
<component type="typeof(App)" render-mode="Server" />
@* for: detect ad blockers *@
<div id="AntiAdblock-nZqKGXDfpEMl">
偵測到 AdBlock 插件這可能影響到某些效能,如: YouTube 影音播放功能,請考慮關閉 AdBlock。
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
@* for: detect ad blockers
ref→[Most effective way to detect ad blockers](https://www.detectadblock.com/)
*@
<script src="/kampyle.js" type="text/javascript"></script>
<script type="text/javascript">
if (!document.getElementById('AntiAdblock-dwZxflhAIjQK')) {
const antiadblock = document.getElementById('AntiAdblock-nZqKGXDfpEMl');
antiadblock.style.display = 'block';
antiadblock.getElementsByClassName('dismiss')[0].onclick = function () {
antiadblock.style.display = 'none';
};
}
</script>
</body>
</html>
Last updated