Disabling DFP / DoubleClick iFrames - javascript

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

Related

How to Inject Adsense

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.

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.

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.

Best place to insert the Google Analytics code [duplicate]

This question already has answers here:
Should I put the Google Analytics JS in the <head> or at the end of <body>?
(8 answers)
Closed 8 years ago.
Where’s the best place to insert the Google Analytics code in WordPress, header or footer? I prefer footer, because I wanted my site to load faster by reducing the number of scripts in the header, but can it work even if the script is in the footer?
Google used to recommend putting it just before the </body> tag, because the original method they provided for loading ga.js was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head> tag.
<head> will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.
As a matter of personal preference, I like to include it in the <head>, but its really a matter of preference.
As google says:
Paste it into your web page, just before the closing </head> tag.
One of the main advantages of the asynchronous snippet is that you can
position it at the top of the HTML document. This increases the
likelihood that the tracking beacon will be sent before the user
leaves the page. It is customary to place JavaScript code in the
<head> section, and we recommend placing the snippet at the bottom of
the <head> section for best performance
If you want your scripts to load after page has been rendered, you can use:
function getScript(a, b) {
var c = document.createElement("script");
c.src = a;
var d = document.getElementsByTagName("head")[0],
done = false;
c.onload = c.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
b();
c.onload = c.onreadystatechange = null;
d.removeChild(c)
}
};
d.appendChild(c)
}
//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
// do stuff after the script has loaded
});
Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

Categories