广告点击添加
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* 广告点击上报:POST /api/app/ads/click(本站 Go 服务代理到上游,appId 由服务端固定为 12)。
|
||||
* - 广告元素由服务端模板输出 data-ads-id / data-ads-location,ID 无效时不输出,即不上报
|
||||
* - document 捕获阶段监听 click 与 auxclick(中键),不阻止默认行为、不影响广告链接打开
|
||||
* - 不依赖 request.js(导航页未加载),失败静默
|
||||
*/
|
||||
(function () {
|
||||
if (window.__adClickBound) return;
|
||||
window.__adClickBound = true;
|
||||
|
||||
var ENDPOINT = "/api/app/ads/click";
|
||||
|
||||
function positiveInt(value) {
|
||||
var text = String(value == null ? "" : value).trim();
|
||||
if (!/^\d+$/.test(text)) return 0;
|
||||
var number = Number(text);
|
||||
return Number.isSafeInteger(number) && number > 0 ? number : 0;
|
||||
}
|
||||
|
||||
function payloadFrom(target) {
|
||||
if (!target || typeof target.closest !== "function") return null;
|
||||
var el = target.closest("[data-ads-id]");
|
||||
if (!el) return null;
|
||||
var adsId = positiveInt(el.getAttribute("data-ads-id"));
|
||||
var location = positiveInt(el.getAttribute("data-ads-location"));
|
||||
return adsId && location ? { adsId: adsId, location: location } : null;
|
||||
}
|
||||
|
||||
function report(payload) {
|
||||
try {
|
||||
fetch(ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
credentials: "same-origin",
|
||||
keepalive: true,
|
||||
}).catch(function () {});
|
||||
} catch (error) {
|
||||
// 上报失败不影响广告跳转。
|
||||
}
|
||||
}
|
||||
|
||||
function onClick(event) {
|
||||
if (event.type === "auxclick" && event.button !== 1) return;
|
||||
var target = event.target;
|
||||
if (target && target.nodeType !== 1) target = target.parentElement;
|
||||
var payload = payloadFrom(target);
|
||||
if (payload) report(payload);
|
||||
}
|
||||
|
||||
document.addEventListener("click", onClick, true);
|
||||
document.addEventListener("auxclick", onClick, true);
|
||||
})();
|
||||
Reference in New Issue
Block a user