Adding Dynamic Ads With Adsense - adsense

I have a page with about 50 blog posts per page. The content for each blog post is hidden with css and is shown when a user clicks on the blog post title. Is there a way to dynamically add adsense content to each blog post when a user clicks on the title? Is it allowed by Google?
I know I can add 50 ads to the page and have them hidden with css until the user clicks on the blog title but that would be very inefficient.
This is what Im trying to do:
Example:
http://jsfiddle.net/WZG2U/
HTML:
<div id="post1">
<h1>Blog Post 1</h1>
<p class="hidden">This is the content for blog post.</p>
</div>
CSS:
body {
padding:30px;
}
* {
font-family:arial;
}
h1 {
font-weight:bold;
cursor:pointer;
font-size:20px;
}
p.hidden {
display:none;
}
div.ad {
float:right;
background-color:red;
height:100px;
width:100px;
color:#ffffff;
font-weight:bold;
font-size:11px;
text-align:center;
}
Script:
$("h1").click(function() {
var thisid = $(this).parent().attr("id");
if ($("div#"+thisid+ " p").hasClass("hidden")) {
$("div#"+thisid+ " p.hidden").removeClass("hidden");
// insert dymanic adsense ad
$("div#"+thisid+ " p").before('<div class="ad">insert dynamic adsense ad here!</div>');
} else {
$("div#"+thisid+" p").addClass("hidden");
$("div#"+thisid+" div.ad").remove();
}
});

It's up to the blog template if it can dynamically add ad code to the content to the page or not. Blogger has a monetize tab for using Adsense ads and it dynamically ads the code to the page at the page creation time. The page must be in plain html, meaning that you must have plain text and not scripted text or else the Adsense bot will have no text to walk to determine ad relevancy to the page and you could be banned for doing so. I mean you weren't trying to write a page entirely in ajax or something like that were you?

Related

TagError: adsbygoogle.push() error: No slot size for availableWidth=0 when i use responsive ads

i have responsive ads set for Adsense
I am getting the error:
uncaught exception: TagError: adsbygoogle.push() error: No slot size for availableWidth=0
on every page that has this code
<style type="text/css">
.adslot_2 { display:inline-block;width: 336px; height: 280px;}
#media (max-width: 336px) { .adslot_2 { width: 300px; height: 250px; } }
#media (min-width: 500px) { .adslot_2 { display: none; } }
</style>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle adslot_2" data-ad-client="removed for security purpose" data-ad-slot="removed for security purpose" data-ad-format="rectangle"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
i tried tampering with the code a lot but still getting the same error
note that i have other responsive ad units with different codes that are not showing this error so i am 100% sure the problem is with the code itself
my objective is to hide the ad from desktop and show it on mobile devices
what is wrong with the code?
There are (basically) two different methods of responsive ad unit "sizing" in Google AdSense.
"Automatic sizing based on the space available" with
data-ad-format. See About responsive ad units page.
"Exact
ad unit size per screen width" with #media queries. See How to
modify your responsive ad code page. (You'll find there are "variations",
different implementations of this method.)
The first one is automatic, the second is "manual".
Usually no method can be automatic and manual at the same time, because there will be a conflict between the two, and I think your code should work fine if you remove data-ad-format="rectangle".
If that works for you, please check again "My ads" > "Ad units" page in your Google AdSense dashboard, and make sure this ad unit ID (data-ad-slot) is listed as "Responsive" - none of the two methods should be used with fixed sized ad units.
I had a similar problem. I noticed that it was because of the banners which had been made invisible based on the size of screen. A solution was to rename the "adsbygoogle" class (I went for 'ADSENSE') to make sure the adsense script wouldn't do anything with the banners before I remove them from the DOM if they were not visible once the stylesheet had been loaded (hence the 'load' event):
window.addEventListener('load', () => {
let matches = document.querySelectorAll("ins.ADSENSE");
Array.from(matches).forEach((element) => {
let parentElement = element.parentElement;
if (window.getComputedStyle(parentElement).getPropertyValue("display") === "none") {
element.remove();
} else {
element.classList.remove("ADSENSE");
element.classList.add("adsbygoogle");
(adsbygoogle = window.adsbygoogle || []).push({});
}
});
});

How create a Facebook share button without SDK or custom app id?

I am looking at the latest update to Facebook's share button.
It seems that it's no longer possible to include a share button in a website without including the Facebook javascript SDK, or having a Facebook app somewhere that provides you with an app id?
Share button example 1 uses the Facebook SDK
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/',
}, function(response){});
Share button example 2 uses a custom app id
https://www.facebook.com/dialog/share?
app_id=145634995501895
&display=popup
&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F
&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer
Question: how to build a plain and simple share button for Facebook with one line of code, that does not require libraries and app id's?
you can use facebook sharer link and a simple popup to do the job
$("#facebookShareLink").on("click",function(){
var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=http://stackoverflow.com", "pop", "width=600, height=400, scrollbars=no");
return false;
});
It is possible. No need for an FB application for a simple sharing of URL. Create a simple pop up window and use Facebook share dialog.
https://developers.facebook.com/docs/sharing/reference/share-dialog
This is still included in their API as of the moment.
window.open("https://www.facebook.com/sharer/sharer.php?u=http://www.gmanetwork.com/news/", "pop", "width=600, height=400, scrollbars=no");
Create function who will center the pop-up every time.
function openURLInPopup(url, width, height, name) {
if (typeof(width) == "undefined") {
width = 800;
height = 600;
}
if (typeof(height) == "undefined") {
height = 600;
}
popup(url, name || 'window' + Math.floor(Math.random() * 10000 + 1), width, height, 'menubar=0,location=0,toolbar=0,status=0,scrollbars=1');
}
Then your link should look like this
For Twitter:
<a class="btn_twitter" onclick="openURLInPopup('http://twitter.com/home?status=http://www.domain.ro/url.html',600, 400); return false;" href="#" target="_blank">Twitter</a>
For facebook:
<a class="btn_fb" onclick="openURLInPopup('http://www.facebook.com/sharer.php?u=http://www.domain.ro/url.html',600, 400); return false;" href="#" target="_blank">Facebook</a>
For Google
<a class="btn_gplus" onclick="openURLInPopup('https://plus.google.com/share?url=http://www.domain.ro/url.html',600, 400); return false;" href="#">gplus</a>
If you want to add your own (possibly dynamic) text, you can add the quote parameter to the link:
https://www.facebook.com/share.php?u=example.com&quote=YOUR+TEXT+HERE

How to detect Adblock on my website?

I would like to be able to detect if the user is using adblocking software when they visit my website. If they are using it, I want to display a message asking them to turn it off in order to support the project, like this website does.
If you enter to that site and your browser has some kind of adblock software enabled, then the site instead of showing the actual ads shows a little banner telling the users that the ad revenue is used for hosting the project and they should consider turning Adblock off.
I want to do that on my website, I'm using adsense ads on it, How can I do that?
My solution is not specific to a certain ad network and is very lightweight. I've been running it in production for a few years. AdBlock blocks all URLs containing the word "ads" or "prebid". So this is what I did:
I added a small js file to my webroot with the name prebid-ads.js
This is the only line of code in that file. Update 2022-04-26 Call this variable something else, see below!
var canRunAds = true;
Then somewhere in your page:
<html>
<head>
<script src="/js/prebid-ads.js"></script>
</head>
<body>
<script>
if( window.canRunAds === undefined ){
// adblocker detected, show fallback
showFallbackImage();
}
</script>
</body>
</html>
Update 2022-04-26 uBlock Origin loads their own ads-prebid.js that reverts the trick described in this answer (proud!), their file contains the following:
(function() {
'use strict';
window.canRunAds = true;
window.isAdBlockActive = false;
})();
As a solution just rename your canRunAds variable to something fun, like window.adsAreWithUs or window.moneyAbovePrivacy.
Discovery and workaround by Ans de Nijs. Thanks!
Supporting extensions
Files like ads.js are blocked by at least these adblockers on Chrome:
AdBlock
Adblock Plus
Adblock Pro
Ghostery
Does not work with:
Privacy Badger
Not a direct answer, but I'd put the message behind the ad to be loaded... rather than trying to detect it, it'd just show up when the ad doesn't.
async function detectAdBlock() {
let adBlockEnabled = false
const googleAdUrl = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'
try {
await fetch(new Request(googleAdUrl)).catch(_ => adBlockEnabled = true)
} catch (e) {
adBlockEnabled = true
} finally {
console.log(`AdBlock Enabled: ${adBlockEnabled}`)
}
}
detectAdBlock()
http://thepcspy.com/read/how_to_block_adblock/
With jQuery:
function blockAdblockUser() {
if ($('.myTestAd').height() == 0) {
window.location = 'http://example.com/AdblockNotice.html';
}
}
$(document).ready(function(){
blockAdblockUser();
});
Of course, you would need to have a landing page for AdblockNotice.html, and the .myTestAd class needs to reflect your actual ad containers. But this should work.
EDIT
As TD_Nijboer recommends, a better way is to use the :hidden (or :visible, as I use below) selector so that display: none is also checked:
function blockAdblockUser() {
if ($('.myTestAd').filter(':visible').length == 0) {
// All are hidden, or "not visible", so:
// Redirect, show dialog, do something...
} else if ($('.myTestAd').filter(':hidden').length > 0) {
// Maybe a different error if only some are hidden?
// Redirect, show dialog, do something...
}
}
Of course, both of these could be combined into one if block if desired.
Note that visibility: hidden will not be captured by either as well (where the layout space stays, but the ad is not visible). To check that, another filter can be used:
$('.myTestAd').filter(function fi(){
return $(this).css('visibility') == 'hidden';
})
Which will give you an array of ad elements which are "invisible" (with any being greater than 0 being a problem, in theory).
Most ads are dynamically loaded in javascript. I just used the onerror event to detect whether the ad script could be loaded or not. Seems to work.
Example with GoogleAds:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" onerror="adBlockFunction();"></script>
This can be used on other elements as well to see if an ad blocker is blocking the content. This method can produce false positives if the remote elements doesn't exist or cannot be reached.
To detect if the user is blocking ads, all you have to do is find a function in the ad javascript and try testing for it. It doesn't matter what method they're using to block the ad. Here's what it looks like for Google Adsense ads:
if(!window.hasOwnProperty('google_render_ad') || window.google_render_ad === undefined) {
//They're blocking ads, display your banner
}
This method is outlined here: http://www.metamorphosite.com/detect-web-popup-blocker-software-adblock-spam
You don't need an extra HTTP request , you may simply calculate the height of a fake add.
By the way, here is a full list matching the elements that adblockers avoid rendering.
window.adBlockRunning = function() {
return (getComputedStyle(document.getElementById("detect"))["display"] == "none") ? true : false;
}()
console.log(window.adBlockRunning);
#detect {
height: 1px;
width: 1px;
position: absolute;
left: -999em;
top: -999em
}
<div id="detect" class="ads ad adsbox doubleclick ad-placement carbon-ads"></div>
My advice is: don't do it!
Any scenario where you treat people as "wrongdoers" is going to result in them fighting back.
Here's my proposal.
Put a small unobtrusive message at the top of the page (regardless of whether ads are being blocked) with the text I *totally* respect your right to block ads and a link to another page/pop-up entitled Read more ....
On the other page, make it clear that you understand it's their computer and they are free to use ad blocking.
Also make it clear in a non-accusatory way that the use of these blockers makes it more difficult for you to deliver great content (explaining why in detail) and that, while you'd prefer the ad blocking to not happen on your site, it's totally their decision. Focus on the positives of turning off blocking.
Those who are vehemently opposed to ads will ignore this but you never stood a chance of convincing them anyway. Those who are indifferent may well be swayed by your appeal since you're not doing the whole "let me get my way or I'll take my ball and go home" thing that honestly should be the exclusive domain of five year old children.
Remember, no-one held a gun to your head and forced you to put your stuff on the net. Treat your readership/users with respect and you'll probably find a good number of them will reciprocate.
My easiest solution with jquery is:
$.ajax({
url: "/scripts/advertisement.js", // this is just an empty js file
dataType: "script"
}).fail(function () {
// redirect or display message here
});
advertisement.js just contains nothing. When somebody uses adblock, it fails and the function gets called.
Just add small script on your site:
var isAdsDisplayed = true;
With name adsbygoogle.js
Then do following:
<script src="/js/adsbygoogle.js"></script>
<script>
if(window.isAdsDisplayed === undefined ) {
// AdBlock is enabled. Show message or track custom data here
}
</script>
Found this solution here
An efficient way to check if there is an adblock:
Simply check if there is adblock enabled by trying to trigger the URL of google ads. If yes then run the callback_has_adblock, if not then run the callback_no_adblock. This solution costs one request more but at least it always works:
var hasAdBlock = function (callback_has_adblock, callback_no_adblock) {
$.getScript( "https://pagead2.googlesyndication.com/pagead/show_ads.js" )
.done(function( script, textStatus ) {
callback_no_adblock();
})
.fail(function( jqxhr, settings, exception ) {
callback_has_adblock();
});
};
This solution works for all kind of ads, not only google adsense.
I know there are already enough answers, but since this question comes up on Google searched for "detect adblock" at the topic, I wanted to provide some insight in case you're not using adsense.
Specifically, with this example you can detect if the default Adblock-list provided by Firefox Adblock is used. It takes advantage that in this blocklist there is an element blocked with the CSS id #bottomAd. If I include such an element in the page and test for it's height, I know whether adblocking is active or not:
<!-- some code before -->
<div id="bottomAd" style="font-size: 2px;"> </div>
<!-- some code after -->
The rest is done via the usual jQuery suspect:
$(document).ready( function() {
window.setTimeout( function() {
var bottomad = $('#bottomAd');
if (bottomad.length == 1) {
if (bottomad.height() == 0) {
// adblocker active
} else {
// no adblocker
}
}
}, 1);
}
As can be seen, I'm using setTimeout with at least a timeout of 1ms. I've tested this on various browsers and most of the time, directly checking for the element in ready always returned 0; no matter whether the adblocker was active or not. I was having two ideas about this: either rendering wasn't yet done or Adblock didn't kick in yet. I didn't bother to investigate further.
They're utilizing the fact that Google's ad code creates an iframe with the id "iframe". So as long as you don't already have something on your page with that ID, this'd work for you too.
<p id="ads">
<script type="text/javascript"><!--
google_ad_client = "their-ad-code-here";
/* 160x600, droite */
google_ad_slot = "their-ad-code-here";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</p>
<script type="text/javascript"><!--
if(document.getElementsByTagName("iframe").item(0) == null)
{
document.write("<div style='width:160px; height:600px; padding-top: 280px; margin-left:5px;border:1px solid #000000; text-align:center; font-family:century gothic, arial, helvetica, sans serif;padding-left:5px;padding-right:5px;'>Advertising seems to be blocked by your browser.<br /><br /><span style='font-size:10px'>Please notice that advertising helps us to host the project.<br /><br />If you find these ads intrusive or inappropriate, please contact me.</span><img src='http://www.playonlinux.com/images/abp.jpg' alt='Adblock Plus' /></div>");
}
--></script>
the safe way is to wrap your ads inside <div> and check the height
<div id="check-ab">
/* your ads code */
</div>
setTimeout(function(){
if(document.getElementById("check-ab").offsetHeight === 0){
console.log("ads blocked");
}
else{
console.log("ads running");
}
}, 100);
it work with adblock plus and bluehell firewall.
I noticed previous comments uses google adsense as object to test. Some pages don't uses adsense, and using adsense block as test is not really a good idea. Because adsense block may harm your SEO.
Here is example how I detect by adblocker simple blocked class:
Html:
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>
Jquery:
$(document).ready(function()
{
if(!$("#ablockercheck").is(":visible"))
{
$("#ablockermsg").text("Please disable adblocker.").show();
}
});
"ablockercheck" is an ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.
AdBlock seems to block the loading of AdSense (etc) JavaScript files. So, if you are using asynchronous version of AdSense ads you can check if adsbygoogle is an Array. This must be checked after few seconds since the asynchronous script is... asynchronous. Here is a rough outline:
window.setTimeout(function(){
if(adsbygoogle instanceof Array) {
// adsbygoogle.js did not execute; probably blocked by an ad blocker
} else {
// adsbygoogle.js executed
}
}, 2000);
To clarify, here is an example of what the AdSense asynchronous ads code looks like:
<!-- this can go anywhere -->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- this is where the ads display -->
<ins class="adsbygoogle" ...></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Notice that adsbygoogle is initialized as an Array. The adsbygoogle.js library changes this array into Object {push: ...} when it executes. Checking the type of variable after a certain time can tell you if the script was loaded.
async function hasAdBlock() {
try {
await fetch("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
method: "HEAD",
mode: "no-cors",
})
return false;
} catch(e) {
return true;
}
}
This approach I use on my site, maybe you will find it helpful. In my opinion, it's the simpliest solution.
AdBlocker blocks specific classes and html elements, by inspecting these selectors of any blocked ads in developer console (they are all listed) you can see which elements will be always blocked.
E.g. just inspect this question page on stackoverflow and you will see bunch of blocked ads.
For example, any element with bottom-ad class is automatically blocked.
I created a non-empty div element with bottom-ad class:
<div class="bottom-ad" style="width: 1px; height: 1px;">HI</div>
After page loads just check if this element is hidden. I used jQuery, but feel free to use javascript:
$('.bottom-ad').css('display') == "none" or even better by using $('.bottom-ad').is(':visible')
If value is true, then AdBlocker is active.
Most adblocker cancel HTTP request to ads.js and make 0px for the element but sometime adblocker removed the DOM, and some answer above will fail because not checking existence of the element.
Using setTimeout() is good practice because without it, will make the script race with adblocker.
The script below will check if dom exist/removed and check offsetHeight of an element if it exist.
setTimeout(function() {
var a = document.querySelector('.showads'),
b = a ? (a.offsetHeight ? false : true) : true;
console.log('ads blocked?', b)
}, 200); // don't too fast or will make the result wrong.
<div class="ads showads">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</div>
This one works good
if there's an adBlocker it will alert you
Simply it sends a header request to a well known ad company for all ad blockers (google ads), if the request is blocked then adbloker exists.
checkAdBlocker();
function checkAdBlocker() {
try {
fetch(
new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
method: 'HEAD',
mode: 'no-cors'
})).catch(error => {
showNotification()
});
} catch (e) {
// Request failed, likely due to ad blocker
showNotification()
}
}
function showNotification() {
alert("Please disable adBlocker")
}
Despite the age of this question, I recently found it very useful and therefore can only assume there are others still viewing it. After looking here and elsewhere I surmised that the main three client side checks for indirectly detecting an ad blocker were to check for blocked div/img, blocked iframes and blocked resources (javascript files).
Maybe it's over the top or paranoid but it covers for ad blocking systems that block only one or two out of the selection and therefore may not have been covered had you only done the one check.
On the page your are running the checks add: (I am using jQuery)
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="advertisement.js"></script>
<script type="text/javascript" src="abds.js"></script>
and add the following anywhere else on the page:
<div id="myTestAd"><img src="http://placehold.it/300x250/000000/ffffff.png&text=Advert" /></div>
I used a div with a bait name as well as an externally hosted image with the text "Advert" and in dimensions used by AdSense (thanks to placehold.it!).
In advertisement.js you should append something to the document which we can check for later. Although it seems like you're doing the same as before, you are actually checking for the file (advertisement.js) itself being loaded, not the output.
$(document).ready(
{
$("body").append("<div id=\"myTestAd2\">check</div>");
});
And then the ad blocker detection script which combines everything
$(document).ready(function()
{
var ifr = '<iframe id="adServer" src="http://ads.google.com/adserver/adlogger_tracker.php" width="300" height="300"></iframe>';
$("body").append(ifr);
});
$(window).on("load",function()
{
var atb = $("#myTestAd");
var atb2= $("#myTestAd2");
var ifr = $("#adServer");
setTimeout(function()
{
if( (atb.height()==0) ||
(atb.filter(":visible").length==0) ||
(atb.filter(":hidden").length>0) ||
(atb.is("hidden")) ||
(atb.css("visibility")=="hidden") ||
(atb.css("display")=="none") ||
(atb2.html()!="check") ||
(ifr.height()!=300) ||
(ifr.width()!=300) )
{
alert("You're using ad blocker you normal person, you!");
}
},500);
});
When the document is ready, i.e. the markup is loaded, we add the iframe to the document also. Then, when the window is loaded, i.e. the content incl. images etc. is loaded, we check:
The dimensions and visibility of the first test div.
That the content of the second test div is "check", as it would have been if the advertimsent.js was not blocked.
The dimensions (and I guess visibility, as a hidden object has no height or width?) of the iframe
And the styles:
div#myTestAd, iframe#adServer
{
display: block;
position: absolute;
left: -9999px;
top: -9999px;
}
div#myTestAd2
{
display: none;
}
Hope this helps
If using the new AdSense code, you can do an easy check, with out resorting to content or css checks.
Place your ads as normal in your markup:
<ins class="adsbygoogle" style="display: block;"
data-ad-client="ca-pub-######"
data-ad-slot="#######"
data-ad-format="auto"></ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
Then you call the adsense code at the bottom of your page (note do not use the "async" flag when calling the adsbygoogle.js script):
<script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Then add this little snippit of code below that:
<script>
if (!adsbygoogle.loaded) {
// do something to alert the user
}
</script>
AdSense always creates/sets the flag adsbygoogle.loaded to true when the ads are loaded, You could place the check in a setTimeout function to delay the check by a few seconds.
html file
<script src="wp-banners.js"></script>
<script>
if(document.getElementById('LavXngdFojBe')){
alert('Blocking Ads: No');
} else {
alert('Blocking Ads: Yes');
}
</script>
wp-banners.js
var e=document.createElement('div');
e.id='LavXngdFojBe';
e.style.display='none';
document.body.appendChild(e);
This is also shown on https://detectadblock.com.
All of the answers above are valid, however most will not work for DNS-level ad blocking.
DNS-level ad blockers(like pi-hole) basically return NXDOMAIN(domain does not exist) for a list of ad blocking domains (e.g. telemetry.microsoft.com will "not exist" when it does).
There are a few ways to circumvent this:
Method A: Request for ads by ip address, not domain.
This method is a bit annoying as you would have to keep track of ip addresses. This will be problematic if your code isn't well maintained or updated regularly.
Method B: Block all requests that fail- even if the client reports NXDOMAIN.
This will be very annoying for users if it is a "legitimate" NXDOMAIN.
if you are using react with hooks:
import React, { useState, useEffect } from 'react'
const AdblockDetect = () => {
const [usingAdblock, setUsingAdblock] = useState(false)
let fakeAdBanner
useEffect(() => {
if (fakeAdBanner) {
setUsingAdblock(fakeAdBanner.offsetHeight === 0)
}
})
if (usingAdblock === true) {
return null
}
return (
<div>
<div
ref={r => (fakeAdBanner = r)}
style={{ height: '1px', width: '1px', visibility: 'hidden', pointerEvents: 'none' }}
className="adBanner"
/>
Adblock!
</div>
)
}
export default AdblockDetect
In case you use jQuery and Google Adsense:
jQuery.getScript(
"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js",
function() {
// Load your ad now
}).fail(function() {
// Google failed to load main script, do something now
});
This is easier to understand: if Google Ads main JavaScript file fails to load, AdSense won't work, so you do something using the fail function of jQuery.
The "Loads your add now" is when I append the "ins" objects, like:
jQuery(".my_ad_div").append('<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxx"
data-ad-slot="xxx"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>');
And in "// Google failed to load main script, do something now" I generally put images in places of ads.
[October 2022 - uBlock Origin, Adblock Plus, Brave browser]
Ad blockers are very smart these days, they can even spoof ad server requests with redirects and return fake responses. Below is the only good solution I've found and it works with even the best ad blocker extensions (like uBlock Origin, Adblock Plus) and in-browser ad blockers (like Brave, Opera) that I've tested. It works with those that block access to the ad server, as well as those that spoof it. It works with any ad provider, not just Google! It uses Google ad service exclusively for detection, because it's blocked by all blockers, its availability is always high and it's fast.
The smartest ad blockers don't block, they redirect requests and return fake 'successful' responses. As of now, Google never redirects the request, so we can detect the redirect and thus the blocker.
Important:
we only send a HEAD request, which runs quickly and does not burden the client's data traffic
adsbygoogle.js must be called with the full original path, which is on the blacklist of every ad blocker (don't copy the js to your own website!)
You can use this solution anywhere (<head>/<body>) and anytime. Try it here directly by hitting Run code snippet in any browser with any ad blocker:
function detectAdblock(callback) {
fetch('https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', {
method: 'HEAD',
mode: 'no-cors',
}).then((response) => {
// If the request is redirected, then the ads are blocked.
callback(response.redirected)
}).catch(() => {
// If the request fails completely, then the ads are blocked.
callback(true)
})
}
detectAdblock((isAdblockerDetected) => {
console.log(`ads are ${isAdblockerDetected ? 'blocked' : 'not blocked'}`)
});
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>var adb=true;</script>
<script src="./getbanner.cfm?"></script>
<script>
$(document).ready(function(){if(adb)alert('AdBlock!');});
</script>
and in getbanner.cfm file:
adb = false;
I think it's easiest way to detect adblock.
I know this is already answered, but I looked at the suggested sample site, and I see they do it like this:
<script type="text/javascript">
if(document.getElementsByTagName("iframe").item(0) == null) {
document.write("<div style="width: 160px; height: 600px; padding-top: 280px; margin-left: 5px; border: 1px solid #666666; color: #FFF; background-color: #666; text-align:center; font-family: Maven Pro, century gothic, arial, helvetica, sans-serif; padding-left: 5px; padding-right: 5px; border-radius: 7px; font-size: 18px;">Advertising seems to be blocked by your browser.<br><br><span style="font-size: 12px;">Please notice that advertising helps us to host the project.<br><br>If you find these ads intrusive or inappropriate, please contact me.</span><br><img src="http://www.playonlinux.com/images/abp.png" alt="Adblock Plus"></div>");
};
</script>
No need for timeouts and DOM sniffing. Simply attempt to load a script from popular ad networks, and see if the ad blocker intercepted the HTTP request.
/**
* Attempt to load a script from a popular ad network. Ad blockers will intercept the HTTP request.
*
* #param {string} url
* #param {Function} cb
*/
function detectAdBlockerAsync(url, cb){
var script = document.createElement('script');
script.onerror = function(){
script.onerror = null;
document.body.removeChild(script);
cb();
}
script.src = url;
document.body.appendChild(script);
}
detectAdBlockerAsync('http://ads.pubmatic.com/AdServer/js/gshowad.js', function(){
document.body.style.background = '#c00';
});

Select a single 'featured' post in Tumblr?

I would like my Tumblr homepage to show a single Question/Answer post that is selected by a 'featured' tag, or rather by being the most recent Question/Answer post tagged 'featured'. I don't see any built in Tumblr tags that will do this.
I am using jQuery to get the featured post (n number of them) from a category 'featured' by default. I have implemented this solution to my theme - Purely
Here is a screen-shot (displaying three featured posts)
Add this line 's meta section
<meta name='text:Featured Tag' content='featured' />
Add jQuery library in
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
Add these lines in where you want to display the featured post
{block:IndexPage}
{block:IfFeaturedTag}
<h1 class="featured-subhead">
Featured Posts +
</h1>
{/block:IfFeaturedTag}
{/block:IndexPage}
Add these lines just before the closing tag
{block:IndexPage}{block:IfFeaturedTag}
<script>
var rssurl = '/tagged/{text:Featured Tag}/rss';
$.get(rssurl, function(data) {
$('.featured-subhead').append('<div class="featured-posts">');
var $xml = $(data);
var vari = 0;
$xml.find("item").each(function() {
var $this = $(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text(),
description: $this.find("description").text(),
pubDate: $this.find("pubDate").text(),
author: $this.find("author").text()
}
vari = vari +1;
if(vari <4){
$('.featured-subhead').append('<div class="featured-post" style="overflow:hidden;"><h2 class="featured-title">' + item.title + '</h2><div class="featured-post-description' + vari + '">' + item.description + '</div><div class="featured-post-link">Read More</div></div>');
//Do something with item here...
}
});
$('.featured-subhead').append('</div>');
});
{/block:IndexPage}{/block:IfFeaturedTag}
You can change if(vari <4){ line according to the numbers of posts you want to display as featured. For example, to display a single post, it would be if(vari <2){ .
I have also added few CSS classes to design the output. This can be declared in segment in
h1.featured-subhead
{
/* Heading of featured post */
}
.featured-posts
{
/* Outer box of all featured posts */
}
.featured-post
{
/* Inner box of each featured post */
}
h2.featured-title
{
/* Heading of each featured post */
}
.featured-post-description
{
/* Description or body of each featured post */
}
.featured-post-link
{
/* Link to Permalink page of each featured post */
}
Here only featured-subhead class is necessary. This must be added to the heading of featured post. jQuery will add the featured posts after that.
How does it work?
No surprises here. Tumblr generates a tag RSS page for each page. By using javascript, I am fetching that specific tag page and displaying 'n' number of elements from the XML elements. Sometimes, Tumblr takes a little more time (I don't know why) to generate the RSS page of newly added tags. Be patient and try to browse your-blog.tumblr.com/tagged/featured/rss page to check it is generated or not.
What you're asking is not a native setting to tumblr, in other words there's no preference setting you can simply check.
In order to do what you describes above, you will either need to edit your current theme code, or code a new theme from scratch.
In order to only show 1 question post, at the top, with a tag of featured, you will need to work with the jQuery/Javascript and the Tumblr API.
It's pretty complex coding, but if you're up for it, head on over to the Tumblr API Codex.
This is a little late, but in case it's of any help: Our free Single A theme has the sticky post feature built in. It's the first (and only) tumblr theme to have it. You can get it here: http://www.tumblr.com/theme/28638 or learn more about it here: http://singleatheme.tumblr.com/. Hope this helps!

Problem in facebook share functionality

I have a facebook iframe application where i have provided a share functionality. I am using this code :
<script>
function fbs_click()
{
u='<?php echo $shareURL;?>';
t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
return false;
}
</script>
<style>
html .fb_share_button {
display: -moz-inline-block; display:inline-block;
padding:1px 20px 0 5px; height:15px; border:1px solid #d8dfea;
background:url(http://b.static.ak.fbcdn.net/rsrc.php/z39E0/hash/ya8q506x.gif)
no-repeat top right;
}
html .fb_share_button:hover {
color:#b5b8d3; border-color:#295582; background:#3b5998
url(http://b.static.ak.fbcdn.net/rsrc.php/z39E0/hash/ya8q506x.gif)
no-repeat top right; text-decoration:none;
}
</style>
Share
The problem i am facing is that if i pass u to my site url then inside share box title is properly displayed but when posted to my profile, clicking on the link redirects me to outside of my facebook application which i don't want i want it to remain inside facebook page.
However if i change u parameter to something like http://apps.facebook.com/app/ then inside share box the title is showing apps.facebook.com and when posted on my profile, clicking on it redirects me inside the facebook application but onto a new tab.
I just want the title should be set according to the value passed and if i click on it on my profile page it should remain inside facebook.
I have found a solution to this problem you have to change the parameters in the window.open and pass the value as urlencode(i have done in php)
I am attaching the changed code:
1)
<?php
$title=urlencode('Facebook Share Platform');
$image=urlencode('imagepath');
$summary=urlencode('Check This Out');
$url=urlencode('http://apps.facebook.com/yourapplication');
?>
2)
window.open('http://www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[summary]=<?php echo $summary;?>&p[url]=<?php echo $url; ?>&&p[images][0]=<?php echo $image;?>', 'sharer', 'toolbar=0,status=0,width=626,height=436');
Hope this helps to others who are facing same issue.
Thanks
def fb_share_knob opts={}
opts.each { |k,v| opts[k] = CGI.escape(v) if v.present? }
sharer_url = "http://www.facebook.com/sharer.php?s=100&p[url]=#{ opts[:url] }&p[title]=#{ opts[:title] }&p[summary]=#{ opts[:summary] }&p[images][0]=#{ opts[:image] }"
<<-FB_SHARE_LINK
<script type="text/javascript">
function fbs_click() {
window.open('#{ sharer_url }','sharer','toolbar=0,status=0,width=626,height=436');
return false;
}
</script>
Share on Facebook
FB_SHARE_LINK
end
Ruby code. Image load problem: if the image you'd like to share is on your test server make sure it's accessible from outside of your firewall