Files
2026-10-29 16:41:17 +07:00

49 lines
1.7 KiB
JavaScript

/**
* 广告点击上报:点击任一带 data-ads-id / data-ads-location 的广告元素时,
* 异步 POST 本站 BFF /api/ads/click(服务端补 appId 并转发 /api/app/ads/click)。
* - 捕获阶段监听 click / auxclick(中键),不 preventDefault,不阻塞广告链接打开
* - id、location 均为正整数才上报;失败静默
*/
(function () {
var ENDPOINT = "/api/ads/click";
function toPositiveInt(value) {
var text = String(value == null ? "" : value).trim();
if (!/^\d+$/.test(text)) return 0;
var n = Number(text);
return n > 0 && n <= 9007199254740991 ? n : 0;
}
function findAdElement(target) {
var el = target && target.nodeType === 1 ? target : target && target.parentElement;
return el && typeof el.closest === "function" ? el.closest("[data-ads-id][data-ads-location]") : null;
}
function report(adsId, location) {
try {
fetch(ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ adsId: adsId, location: location }),
credentials: "include",
keepalive: true,
}).catch(function () {});
} catch (error) {
// 上报失败静默,不影响广告跳转。
}
}
function onClick(event) {
if (event.type === "auxclick" && event.button !== 1) return;
var el = findAdElement(event.target);
if (!el) return;
var adsId = toPositiveInt(el.getAttribute("data-ads-id"));
var location = toPositiveInt(el.getAttribute("data-ads-location"));
if (!adsId || !location) return;
report(adsId, location);
}
document.addEventListener("click", onClick, true);
document.addEventListener("auxclick", onClick, true);
})();