How do I hide certain elements on my page, based on referral traffic?
More specifically, how do I hide ads? I pose this question after reading this: coding horror entry
In it, he states
As a courtesy, turn off ads for Digg, Reddit, and other popular referring URLs. This audience doesn't appreciate ads, and they're the least likely to click them anyway.
I agree with what he says. So how do I do this?
I'd use PHP for this, as JavaScript code to hide ads will make you look like you're hiding the ads for everyone and just gaining revenue from them (Google is smart, so they'll find you for doing something like that).
With PHP, however, you can modify the page before it reaches the user, eliminating that problem. Basically, you conditionally check where the browser came from:
<?php
$sites = array("reddit.com", "digg.com");
if (!in_array(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST), $sites)) :
?>
<div>your ads</div>
<?php else:?>
<div>Hello reddit person</div>
<?php endif; ?>
You'll have to make your site run PHP code (it'll be dynamic) to conditionally display your ads. This code won't work, though, as reddit
isn't a URL, but you get the idea; check the URL for reddit.com
.
那么,我不知道你的网站是如何处理广告的,但是在StackOverflow上它可能是类似的东西
function hideAds()
{
var elems = document.getElementsByClassName( "everyonelovesstackoverflow" )
for( var i = 0; i < elems.length; i++ )
elems[ i ].parentNode.removeChild( elems[ i ] )
}
// change the logic as you like. You may need to parse document.referrer
if( document.referrer == <some referrer url> ) hideAds()
You will want to show ads if appropriate, not hide ads if inappropriate -- or else you are probably violating the terms of AdSense, eg hiding ads after they're displayed. At the very least, wait to display the ads until you check the referrer (may also be violating the terms, but much less likely). Also review the terms of your ad service to ensure that using a client-side technology like javascript to dynamically display ads is not against the terms.
To answer your question, just detect the HTTP Referrer (the field is actually called the HTTP "Referer", which is a misspelling) and insert ads if it's not from the websites you "like". For API / examples, you can google for http referrer your_language
. For example, in PHP it is $_SERVER['HTTP_REFERER']
. In python, it depends on the web framework you're using. As someone else mentions in javascript it is document.referrer
, etc. Javascript is the easiest solution, but once again, read the terms.
上一篇: numpy中的3D数组的2D切片系列