Dynamic Adsense Insertion With JavaScript
Asked Answered
B

9

36

I can't believe how hard this is to find, but even in the Google developer docs I can't find it. I need to be able to dynamically, only with JavaScript insert adsense. I also looked on StackOverflow and some others have asked this but no response. Hopefully this will be a better explanation and will get some replies.

Basically, a user inserts my script, lets call it my.js (can't say what it is specifically at the moment.) my.js is loaded and in my.js some embedded media is displayed on their page then I need somehow to append the generated HTML from:

<script type="text/javascript"><!--
google_ad_client = "ca-pub-xxx";
/* my.js example Ad */
google_ad_slot = "yyy";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

Inside a specific <div> (or whatever) element. Any ideas?

P.S. No libraries like jQuery, and I can't insert HTML onto the page unless it's through JavaScript and it has to be inserted into a specific <div> i named (I'm using Sizzle for my JS library if that helps)

Biogeography answered 1/6, 2011 at 7:37 Comment(0)
P
24

The simple technique used to asynchronously load the AdSense script proposed by other answers won't work because Google uses document.write() inside of the AdSense script. document.write() only works during page creation, and by the time the asynchronously loaded script executes, page creation will have already completed.

To make this work, you'll need to overwrite document.write() so when the AdSense script calls it, you can manipulate the DOM yourself. Here's an example:

<script>
window.google_ad_client = "123456789";
window.google_ad_slot = "123456789";
window.google_ad_width = 200;
window.google_ad_height = 200;

// container is where you want the ad to be inserted
var container = document.getElementById('ad_container');
var w = document.write;
document.write = function (content) {
    container.innerHTML = content;
    document.write = w;
};

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://pagead2.googlesyndication.com/pagead/show_ads.js';
document.body.appendChild(script);
</script>

The example first caches the native document.write() function in a local variable. Then it overwrites document.write() and inside of it, it uses innerHTML to inject the HTML content that Google will send to document.write(). Once that's done, it restores the native document.write() function.

This technique was borrowed from here: http://blog.figmentengine.com/2011/08/google-ads-async-asynchronous.html

Pungy answered 5/4, 2013 at 18:53 Comment(8)
Have not tested it, but it sounds reasonable. Nice work-around. On the other hand, this technique could be pre-empted with suitable programming from within the google-ads code...Drouin
@enRaiser I hate doing these things as much as you do, and you certainly don't have to use it. :-) But it saved me when I was in a bind. It allowed me to move on to solving real business problems instead of fighting with AdSense's script which I couldn't control.Pungy
@Irina Google's still using document.write() in 2021?Pungy
@JohnnyOshika seems like yes, because I haven't found any other solution how to make it work when I want to insert it dynamically.Dominant
@JohnnyOshika oh mamma mia, the answer is from 2013!Dominant
@Dominant well I'm glad it worked!Pungy
Using Pagespeed you can see Google is still using document.write() even 2022 but this scrimt seems not to work anymore :(Oleograph
@Oleograph very strange. I can't see why it wouldn't work if you need document.write() to work after being loaded asynchronously.Pungy
S
14

I already have adsense on my page but also inject new ads into placeholders in my blog article. Where I want an advert injecting I add a div with a class of 'adsense-inject' then I run this script when the doc is ready and I know the adsense script has already been loaded for the other adverts:-

    $(document).ready(function()
    {
        $(".adsense-inject").each(function () {
            $(this).append('<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3978524526870979" data-ad-slot="6927511035" data-ad-format="auto"></ins>');
            (adsbygoogle = window.adsbygoogle || []).push({});
        }); 
    });
Spacetime answered 29/3, 2016 at 5:27 Comment(3)
Great - this solution is the simplest and least invasive. Works for me.Henni
Hi, can you explain to me what does this do: (adsbygoogle = window.adsbygoogle || []).push({});Boom
@VladimirKostov, this is directly from the code that is provided to be used by AdSense. I would wager it's purpose is for the client page to communicate to the AdSense script the ads that need to be rendered. Doing it in this fashion allows for the ads to be queued while the adsense rendering script is loaded asynchronously in the background.Gilboa
T
4

Here is an updated implementation, this is useful if you need no manage the Ads using a common external javascript include, in my case I have a lot of static html files and it works well. It also offers a single point of management for my AdSense scripts.

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); 

Example of usage:

<script type="text/javascript" src="/adinclude.js"></script>
Tirrell answered 18/1, 2018 at 11:47 Comment(1)
This is an elegant rewrite of the official Google tags. Works flawlessly with Vue.js.Pilau
L
3

What about having the vars (google_ad_client, etc) always in the head and dynamically append the other part like this:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
myDIV.appendChild(script); 
Lovelorn answered 17/2, 2012 at 13:56 Comment(0)
D
1

According to this page, it is possible to generate script tags and populate their src fields on the fly - which is what @noiv suggests (my version here should be self-contained; no external html or js libraries required). Have you tried this out? It does not seem so difficult...

function justAddAdds(target_id, client, slot, width, height) {
  // ugly global vars :-P
  google_ad_client = client;
  google_ad_slot = slot;
  google_ad_width = width;
  google_ad_height = height;
  // inject script, bypassing same-source
  var target = document.getElementById(target_id);
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
  target.appendChild(script);
}
Drouin answered 1/8, 2012 at 19:6 Comment(5)
This was a long time ago, but there was a problem with inserting it dynamically. I'm sure there was the reason on another SO thread, but yeah, it didn't work with the adsense script a year ago anyway. Have you tried recently?Biogeography
Not with adsense, but I have just verified that this allows you to execute arbitrary external JS within Jsfiddle...Drouin
Yes :) i know it works for random files, but there was a specific reason it didn't work for adsense which I can't remember now since it's been quite awhileBiogeography
Still, it is an interesting tool to have. Sort of the poor man's XmlHttpRequest...Drouin
This technique won't work with AdSense because AdSense uses document.write inside of the script. document.write only works during page creation, and because you're loading the script asynchronously, the page creation process will have already completed when the AdSense script executes. Until Google stops using document.write, this technique won't work. More info on document.write here: https://mcmap.net/q/42169/-why-is-document-write-considered-a-quot-bad-practice-quotPungy
A
1

OK, this seems to work for me, but as always, if Google change their model, this may become deprecated and no longer work. It simply required stripping the standard code that Google supplies into its 3 constituent parts, which are...

  1. The Google JS script link (include this once on your overall page.): <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

  2. The <ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="GOOGLE_KEY" data-ad-client="GOOGLE_CLIENT" data-ad-slot="GOOGLE_AD_ID"></ins> tag that contains the original definition provided by Google. This is what you will place into your DOM wherever you need it via your JS build code. I tend to simply insert it as a string using .innerHTML, but you could do a document.createElement and manually add all the attributes depending on your requirements. I personally find no discernible advantage to either way, so it boils down to taste IMHO.

  3. Once you have built your page (via your javascript code), finally make the call to build the Google Ad: (adsbygoogle = window.adsbygoogle || []).push({});

This method works for me great where I can place the Google Ad <ins></ins> tag mid list when building paginated results by looping through an AJAX JSON result set (for example) and then once the list has been built, I then make the Google JS call (3 above). AND it allows for me to rebuild a list and recall the Google Ad build (3 above) as many times as I want (e.g. next page or changing number per page).

Hope this helps.

Araucanian answered 22/12, 2019 at 17:42 Comment(0)
K
0

It's kind of funny. I was confused too. Adsense told us:

Copy and paste the ad unit code in between the body tags of your pages

Place this code where you want an ad to appear. Do this for each individual ad unit, on every page.

It means we should implenment like this:

$.ajax('/api/xxx',
  function(data) {
    var container = $("#container")
    for (var item of data) {
      container.append( handleItem(item) );
    }
    // and append ALL the code, include two script tags and one ins tag.
    container.append(
`<div>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<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>
</div>`)
  }
)

😂😂😂, just paste whole sample code for all places you want to show the ad.

Kuster answered 12/4, 2020 at 3:48 Comment(0)
O
0

You can load adsense with setTimeout("adsenseladen()", 1); if Consent if given.

 <script type="text/javascript">
 function adsenseladen() {
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
 document.body.appendChild(script);
 }
 </script>


 <ins class="adsbygoogle"
 style="display:block"
 data-ad-client="ca-pub-##########"
 data-ad-slot="##########"
 data-ad-format="auto"
 data-full-width-responsive="true"></ins>

 <script>
 (adsbygoogle = window.adsbygoogle || []).push({});
 </script>
Oleograph answered 3/2, 2022 at 9:39 Comment(0)
B
-2

These methods will work but they will not work for https. If you want to place ads dynamically and use https you will need to sign up for Double Click For Publishers.

I had this problem on my site so I put together an npm module to solve this problem for myself. Hope you find it useful.

Use Adsense in Single Page Web Apps

The link contains full sample code of how to use the module in a single page web app.

Once you have the module installed this code will display your ad in the element you specify: ViceView.showAdsense({adslot: {slot: "myslot", sizes: "[300,100]", id:"your adsenseid"}, element: "element", adwidth: 300, adheight: 100});

Boys answered 9/2, 2016 at 5:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.