仅向Facebook来源访客展示广告:请求修复失效的AdSense脚本
Fix: Show AdSense Ads Only to Facebook Referrers
Hey there, let's get this script working properly! Your original code has a few small issues that are probably preventing it from behaving as expected. Here's the breakdown of what was wrong and the fixed version:
Key Issues in the Original Code
- The initial
<ins>element hasdisplay:blockset by default, which means the ad will show even if the visitor isn't coming from Facebook (the script only sets it toinline-blockwhen the referrer matches, but doesn't hide it otherwise). - The referrer check is too broad—using
/facebook/might match unrelated sites that include "facebook" in their URL. We need a more precise regex to target actual Facebook domains. - There's no handling for cases where the referrer is empty (like a direct visit), and the ad initialization logic is missing a step to trigger the ad load after injecting the script.
Fixed Script
<!-- Hide the ad block by default --> <ins class="adsbygoogle" style="display:none" data-ad-client="ca-pub-XXXXXXXXXXXXXXX" data-ad-slot="4357587803" data-ad-format="auto" data-full-width-responsive="true"></ins> <script type="text/javascript"> // Check if the referrer is from a Facebook domain const isFromFacebook = document.referrer.match(/(facebook\.com|m\.facebook\.com|fb\.me)/i); if (isFromFacebook) { // Show the ad block const adBlock = document.getElementsByClassName('adsbygoogle')[0]; adBlock.style.display = 'block'; // Load Adsense script only if it hasn't been loaded yet if (!document.querySelector('script[src*="pagead/js/adsbygoogle.js"]')) { const script = document.createElement('script'); script.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"; script.async = true; const firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); // Initialize the ad once the script loads script.onload = function() { (adsbygoogle = window.adsbygoogle || []).push({}); }; } else { // If script is already loaded, just initialize the ad (adsbygoogle = window.adsbygoogle || []).push({}); } } </script>
What Changed?
- Default Hidden State: The
<ins>element starts withdisplay:noneso it's hidden unless we explicitly show it for Facebook referrers. - Precise Referrer Check: The regex now targets specific Facebook domains (
facebook.com,m.facebook.com,fb.me) and uses theiflag to ignore case (covers uppercase variants likeFACEBOOK.COM). - Avoid Duplicate Script Loading: We check if the Adsense script is already present on the page before injecting it—this prevents errors from loading it multiple times.
- Ad Initialization: Added
(adsbygoogle = window.adsbygoogle || []).push({})to trigger the ad load, either after the script finishes loading or immediately if it's already there.
This should ensure that the ad only displays when visitors come from Facebook, and loads properly without conflicts.
内容的提问来源于stack exchange,提问作者Benslimane Farouk
相关产品推荐
相关产品推荐

