How to Inject Adsense - javascript

I am trying to figure out why injected Adsense units don’t show up on a page when the client id is changed.
What I am Doing
I use a script I found on a similar stack overflow question and inject an Adsense ad and script into a website, which already runs Adsense, after page load: dynamic Adsense
var externalScript = document.createElement("script");
externalScript.type = "text/javascript";
externalScript.setAttribute('async','async');
externalScript.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
document.getElementsByTagName('body')[0].appendChild(externalScript);
var ins = document.createElement("ins");
ins.setAttribute('class','adsbygoogle');
ins.setAttribute('style','display:block;');/*add other styles if required*/
ins.setAttribute('data-ad-client','ca-pub-YOUR-CLIENTID');
ins.setAttribute('data-ad-slot','YOUR-SLOTID');
ins.setAttribute('data-ad-format','auto');
document.getElementsByTagName('body')[0].appendChild(ins);
var inlineScript = document.createElement("script");
inlineScript.type = "text/javascript";
inlineScript.text = '(adsbygoogle = window.adsbygoogle || []).push({});'
document.getElementsByTagName('body')[0].appendChild(inlineScript);
The Problem
This script injects ads if I set the client id and ad slot to one that is already on the page. However, if I change the client id or ad slot, the element is objected but no ad is loaded. It should be mentioned that I inject after page load.
My Question
Does anyone know why some ads load and some don’t given the parameters I explained earlier?
Please note: I am aware Adsense injection is against the TOS. I do not intent to misuse this method, but am experimenting to discover how it works.

Related

I found a unknown script in blogger theme

Can someone familiar with blogger tell me what is this script doing?
<script type="text/javascript">
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//pagead2.googlesyndication.com/pagead/js/google_top_exp.js';
var head = document.getElementsByTagName('head')[0];
if (head) {
head.appendChild(script);
}})();
</script>
I tried to see what in this file //pagead2.googlesyndication.com/pagead/js/google_top_exp.js is, but the code is minified and hard to read.
I found out the answer.
The code is from blogger navigation bar.
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//pagead2.googlesyndication.com/pagead/js/google_top_exp.js';
var head = document.getElementsByTagName('head')[0];
if (head) {
head.appendChild(script);
}})();
1) This is an anonymous self invoked function.
2) in this function, You are creating a script element:
script = document.createElement('script');
3) giving an src for the js file:
script.src = '//pagead2.googlesyndication.com/pagead/js/google_top_exp.js';
4) getting element head:
var head = document.getElementsByTagName('head')[0];
5) then if there is a head element contained in the document then append the script element to the head
if (head) {
head.appendChild(script);
}})();
I created a blogspot educational blog a couple of days ago and also redirected it to a custom domain. I published two blog posts on it.
One day, I was visiting the blog and had the Ad-blocker ON on the site, I was that it was blocking 1 ad. When I whitelisted the website, it showed nothing.
Then, going to the "view source" option. I came across the same script you are talking about.
I was shocked because who wants any code to appear on site without any permission. Then, I researched it and came to know that it code automatically appears on every newly created blog (the blogspot blog). This is highly likely to appear when you create a blog and do nothing (i.e. when you do not post on the regular basis).
The code on my theme is located under:
<div id="navbar-iframe-container">
So, if you want it to go away, you should publish around 2-3 posts every day and it will be long gone. By the way, even if it is there, it is not going to do anything bad, nor will it show an ad on your blog.
Its inserted by blogger. Try removing it from the theme using theme > 'edit html' and then save and refresh the script will appear again. I think its probably injected by blogger itself. And when you run the page, it usually shows as
window['google_empty_script_included'] = true;
So probably its used for adsense, and shouldn't be something to worry about.

Why create script tag via Javascript, instead of using defer or async script tag attributes?

Some Web applications (I'm thinking about Disqus and LiveFyre) create <script> tags via Javascript, and via Javascript specify that the new scripts be loaded asynchronously. Why do they create the tags via Javascript? Instead of simply doing:
<script src="..." async>
An example:
This is how Disqus instructs website owners to load comments:
<script type="text/javascript">
var disqus_shortname = ...
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] ||
document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
And the src = ...disqus.com/embed.js address is simply a redirect to a static script on another Disqus server, apparently independent of the disqus_shortname.
Why not instead tell people to use this piece of code:
<script>
var disqus_shortname = ...
</script>
<script src="http://direct-address-to-the-embed.js-script" async>
Or even simpler, just one line:
<script src="http://the_disqus_shortname.disqus.com/embed.js" async>
?
(P.S. I added one answer below. Please do add other answers too :-))
My guess is that Disqus (and other services) want to ensure that their scripts doesn't slow down loading of user sites whenever you put their script (probably many CMSes put scripts in a head element).
If you always put your scripts at the end of a body element then writing short version may be optimal:
...
<script>var disqus_shortname = ...</script>
<script src="//shortname.disqus.com/embed.js" async>
</body>
I'm not sure though!
I can think of one uncertain (no. 1) and two likely reasons (no. 2 and 3):
[Edit] But reasons 2 and 3 are moot points — Disqus could simply do this despite of my reasons 2 and 3:
<script src="http://the_disqus_shortname.disqus.com/embed.js" async>
[/Editi]
(Perhaps old browsers that doesn't understand the async attribute completely ignore the whole <script ... async> tag? Instead of ignoring only async and loading the script synchronously?)
Perhaps Disqus would like to be able to genereate the embedded script dynamically, or redirect to different scripts, depending on website settings (although it seems as if Disqus currently always redirects to the same embed.js script always). Without having users reconfigure their Disqus code.
Using a redirect allows Disqus to tell the browser to cache the-scripts-that-is-redirected-to for a long amount of time, but at the same time makes it possible to quickly redirect to another script. At the cost of 1 redirect per download / fetch-from-browser-cache. This was suggested here: https://stackoverflow.com/a/10098250/694469
This is a bit old but still relevant, the main reason we do it is because some tools, such as google-tag-manager, don't accept scripts with certain properties set on them.
e.g. if you try to set the refferer-policy to 'unsafe-url' then google tag manager will just ignore your request to add the <script> tag.

Why do I need to use document.write instead of DOM manipulation methods?

I'm trying a new ad service, and as far as I know they don't provide a functional interface to loading their ads. We want to display different ad sizes depending on the user's screen size, and this service requires you to load a different .js URL for each size.
I originally tried writing:
<script type="text/javascript"><!--
var dochead = document.getElementsByTagName('head')[0];
var newscript = document.createElement('script');
newscript.type = "text/javascript";
newscript.src = '//ads-by.madadsmedia.com/tags/22430/9194/async/' + (screen.width >= 1360 ? '160' : '120') + 'x600.js';
dochead.appendChild(newscript);
//-->
</script>
but I just got a blank page. I looked in Chrome developer tools and it seemed to be loading their script properly. Their script loads other scripts from Google, and they showed up in the DOM as well. But there was no ad image.
When I changed my script to:
<script language="JavaScript" type="text/javascript">
var prot = document.location.protocol;
var adwidth = (screen.width >= 1360 ? '160' : '120');
document.write('<script language="JavaScript" type="text/javascript"'); document.write('src="'+prot+'//ads-by.madadsmedia.com/tags/22430/9194/async/'+adwidth+'x600.js">'); document.write('<\/scr' + 'ipt>');
</script>
it worked properly. I don't generally like using document.write, I wonder why it's needed in this case? The ad service's script makes extensive use of document.write, is that why?
Because they are using document.write():
http://ads-by.madadsmedia.com/tags/22430/9194/async/160x600.js:
if (!window.ActiveXObject){
document.write("<div style=\"text-align: center; margin: 0px auto; width:160px; height:600px; position:relative;\">");
// etc.
If document.write() isn't run in-line on and actively "open" document, it'll clobber what's there. So, running their script post-load overwrites your content with theirs.
if their script uses document.write it is possible that it would cause the page to go blank, as it overwrites the stream.
document.write clears page
You could override document.write as a fix: (but I wouldn't.....)
How to deal with document.write in a script that's added after a page has loaded?
if the document is loading its ready state is interactive but the body element has not been completely parsed. You can not add a child to an element which has not been loaded. It results in an error and the script stops.
dochead.appendChild(newscript);
The quick fix is to run your function using a body.onload event. Moving the script to the bottom of the page may work but I would not consider that reliable in a world which includes Internet Explorer and badly behaving browsers.

Disabling DFP / DoubleClick iFrames

In Google DFP (DoubleClick) you are given an ad code to put in your header and another for your body. When I apply this given ad tag / code to my website, whether its asynchronous or synchronous the ad always displays within an iframe. I'm wondering how I would disable the iFrame.
Here is the generated header code via DFP:
<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>
<script type='text/javascript'>
googletag.cmd.push(function() {
googletag.defineSlot('/16569348/ad-test-1', [400, 267], 'div-gpt-ad-1362958263281- 0').addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
</script>
Here is the generated body code via DFP:
<!-- ad-test-1 -->
<div id='div-gpt-ad-1362958263281-0' style='width:400px; height:267px;'>
<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1362958263281-0'); });
</script>
</div>
Here is the jsFiddle showcasing this problem (inspect element in google chrome to see iframe):
http://jsfiddle.net/EptwH/
Again, I'd like to remove the iframe (and keep the image / ad of course)... any help would truly be appreciated. :)
From DFP's website: link
When you are using Google Publisher Tags (GPT), your ads will automatically load into iframes.
We had the same issue, as our goal was to add native ads directly to the host page DOM and not an IFRAME to gain full responsiveness. We came up with a solution, where we're posting the ad content string to the host page using messages. This way there is no more IFRAME.
For details please see http://insights.burda-studios.de/howto-run-fully-responsive-doubleclick-native-ads-without-iframes/
Please note, that we only run house ads using this approach, not any 3rd party ads where this could lead to unexpected behaviours.
I'm working for a digital advertiser and you never should disable iFrames coming from advertising.
ADS can inclusce harmfull scripts, so best would be using Safeframe (frame using src poining to foreign origin) to prevent that.
Also many ad script use document.write, and inside their iframe they can do that without problem, would they do that on main window after document.ready that would paint your page blank.
Google loads its ads into iframes purposely, this is by design.
This is done because it both allows your page to load faster and to have sand-boxed styles and scripts etc. The render of the page is faster because iframes enable asynchronous loading and rendering of the ad content.
It is possible to "bust" out of the iframe with your ad code if you want, so there is no real disadvantage to the ads being in an iframe, show us an example of what you are trying to do if you have run into a problem
Here is some more reading to do with this.
Part of your question (whether its asynchronous or synchronous) is wrong in my experience.
Not sure if this has changed or if you failed to let the GPT tags run synchronously, but since I changed to synchronous mode, iframes are no longer used.
See for yourself at belmodo.tv

Running a Javascript file (Adsense) after page load

I'm trying to run Adsense after the page has loaded. But inserting the Adsense script file into an element doesn't seem to run it. Here is the version without window.onload (I modeled it after the Analytics script):
<script type="text/javascript">
// adsense variables
google_ad_client = "my-pubid";
google_ad_slot = "my-adslot";
google_ad_width = 728;
google_ad_height = 90;
(function() {
var ad = document.createElement('script');
ad.async = true;
ad.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
var s = document.getElementById('ad_top');
s.appendChild(ad);
})();
</script>
The onload version is the same, just wrapped in window.onload. Checking Chrome dev tools, the script is inserted in the #ad_top div but no ads show. I've tried moving the variables to the very top of the page and it still doesn't display even though the script is inserted fine.
Note: I'm not interested in loading it inline at the bottom of the page and moving it (as in an answer to a related question), I don't want to start loading anything until after the page has fully loaded.

Categories