如何实现用户首次访问时自动显示AdSense Vignette Ads且关闭按钮可用
问题
AdSense Vignette Ads是AdSense的自动广告类型之一,原本需用户点击网站内特定标签链接时才会显示。需求是实现用户首次访问网站时自动展示该广告,当前已在页脚添加脚本,广告能自动显示,但关闭按钮无法正常工作。
现有代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> jQuery(document).ready(function() { var t; if (jQuery) { console.log('Init page Loaded'); console.log('jQuery version : ' + jQuery().jquery); t=setInterval(init,2500); } else { console.log('Init page Not Loaded'); } function init(){ if ($("ins")[0]){ console.log('init complete'); jQuery('.adsbygoogle, .adsbygoogle-noablate').css("display", "inline"); clearInterval(t); //setInterval(init2,5000); } else { console.log('init not complete'); } } function init2(){ jQuery('.adsbygoogle, .adsbygoogle-noablate').remove(); } var ifr = document.getElementById("google_esf"); var isMouseIn; ifr.addEventListener('mouseenter', () => { isMouseIn = true; }); ifr.addEventListener('mouseleave', () => { isMouseIn = false; }); window.document.addEventListener("visibilitychange", () => { if (isMouseIn && document.hidden) { console.log("Click Recorded By Visibility Change"); } }); window.addEventListener("beforeunload", (event) => { if (isMouseIn) { console.log("Click Recorded By Before Unload"); } }); }); </script>
问题分析
当前脚本通过强制设置广告元素的display: inline来强制显示广告,这会破坏AdSense原生的广告交互逻辑——包括关闭按钮的事件绑定和隐藏逻辑,直接导致关闭按钮失效。此外,手动修改广告元素样式不符合AdSense的使用规范,存在触发政策风险。
解决方案
正确的做法是触发AdSense原生的Vignette广告展示逻辑,而非手动操控广告元素样式。以下是修改后的实现:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> jQuery(document).ready(function() { // 轮询检查AdSense API是否加载完成 var checkAdSenseLoaded = setInterval(function() { if (typeof googletag !== 'undefined' && googletag.apiReady) { clearInterval(checkAdSenseLoaded); // 触发首次访问的Vignette广告 triggerVignetteAd(); } }, 500); function triggerVignetteAd() { // 通过localStorage控制仅首次访问触发广告 if (!localStorage.getItem('hasSeenVignette')) { localStorage.setItem('hasSeenVignette', 'true'); // 延迟触发,模拟符合规范的用户间接交互 setTimeout(function() { // 触发AdSense原生广告刷新逻辑 if (googletag.pubads()) { googletag.pubads().refresh(); } }, 1000); } } // 保留原有的点击记录逻辑(按需保留) var ifr = document.getElementById("google_esf"); var isMouseIn; if (ifr) { ifr.addEventListener('mouseenter', () => { isMouseIn = true; }); ifr.addEventListener('mouseleave', () => { isMouseIn = false; }); } window.document.addEventListener("visibilitychange", () => { if (isMouseIn && document.hidden) { console.log("Click Recorded By Visibility Change"); } }); window.addEventListener("beforeunload", (event) => { if (isMouseIn) { console.log("Click Recorded By Before Unload"); } }); }); </script>
关键说明
- 放弃手动修改样式:不再强制设置广告元素的
display属性,依赖AdSense原生逻辑渲染广告,确保关闭按钮的交互功能正常。 - 首次访问控制:用
localStorage标记用户是否已看过广告,避免重复触发。 - 符合AdSense规范:通过延迟触发+原生API刷新的方式,模拟符合政策要求的触发逻辑,规避违规风险。
- 依赖API初始化:等待AdSense的
googletagAPI加载完成后再触发广告,保证广告能正常初始化。
内容的提问来源于stack exchange,提问作者Muhammad Anas
相关产品推荐
相关产品推荐

