使用 JavaScript 进行动态 Adsense 插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6197768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:42:16  来源:igfitidea点击:

Dynamic Adsense Insertion With JavaScript

javascriptapiadsensesizzle

提问by Oscar Godson

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, onlywith 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.

我不敢相信这有多难找到,但即使在 Google 开发人员文档中我也找不到。我需要能够动态地,用 JavaScript 插入 adsense。我还查看了 StackOverflow,其他一些人也问过这个问题,但没有回应。希望这将是一个更好的解释,并会得到一些答复。

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

基本上,用户插入我的脚本,让我们调用它my.js(目前不能说它具体是什么。)my.js加载并在my.js一些嵌入式媒体中显示在他们的页面上然后我需要以某种方式附加生成的 HTML:

<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?

在特定<div>(或其他)元素内。有任何想法吗?

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 Sizzlefor my JS library if that helps)

PS 没有像 jQuery 这样的库,我不能将 HTML 插入页面,除非它是通过 JavaScript 并且必须插入到<div>我命名的特定中(如果有帮助,我将Sizzle用于我的 JS 库)

回答by Johnny Oshika

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.

用于异步加载其他答案提出的 AdSense 脚本的简单技术将不起作用,因为 Googledocument.write()在 AdSense 脚本内部使用。document.write()仅在页面创建期间有效,并且在异步加载的脚本执行时,页面创建已经完成。

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:

要使这项工作发挥作用,您需要进行覆盖,document.write()以便在 AdSense 脚本调用它时,您可以自己操作 DOM。下面是一个例子:

<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 innerHTMLto inject the HTML content that Google will send to document.write(). Once that's done, it restores the native document.write()function.

该示例首先将本机document.write()函数缓存在局部变量中。然后它会覆盖document.write()并在其中innerHTML注入 Google 将发送到的 HTML 内容document.write()。完成后,它会恢复本机document.write()功能。

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

这种技术是从这里借用的:http: //blog.figmentengine.com/2011/08/google-ads-async-asynchronous.html

回答by Stephen Garside

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:-

我已经在我的页面上安装了 Adsense,但还在我的博客文章中将新广告注入了占位符。在我想要广告注入的地方,我添加了一个带有“adsense-inject”类的 div,然后在文档准备就绪时运行此脚本,并且我知道已经为其他广告加载了 adsense 脚本:-

    $(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({});
        }); 
    });

回答by Matteo Conta

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.

这是一个更新的实现,如果您不需要使用常见的外部 javascript 包含管理广告,这将很有用,在我的情况下,我有很多静态 html 文件并且它运行良好。它还为我的 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); 

Example of usage:

用法示例:

<script type="text/javascript" src="/adinclude.js"></script>

回答by Torsten Becker

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

让 vars(google_ad_client 等)始终在头部并像这样动态附加其他部分怎么样:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
myDIV.appendChild(script); 

回答by tucuxi

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...

根据这个页面,可以生成脚本标签并动态填充它们的 src 字段 - 这是@noiv 建议的(我这里的版本应该是自包含的;不需要外部 html 或 js 库)。你试过这个吗?好像没那么难……

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

回答by Andrew Foster

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...

好吧,这似乎对我有用,但与往常一样,如果谷歌改变他们的模型,这可能会被弃用并且不再有效。它只需要将 Google 提供的标准代码剥离成它的 3 个组成部分,它们是……

  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.createElementand 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({});

  1. Google JS 脚本链接(在整个页面上包含一次。): <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

  2. <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>包含 Google 提供的原始定义的标签。这就是您将通过 JS 构建代码将其放入 DOM 中的任何地方。我倾向于简单地使用 将其作为字符串插入.innerHTML,但您可以执行 adocument.createElement并根据您的要求手动添加所有属性。我个人认为这两种方式都没有明显的优势,所以归结为恕我直言。

  3. 构建页面后(通过 JavaScript 代码),最后调用构建 Google 广告: (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).

这种方法对我非常有用,我可以在<ins></ins>通过循环遍历 AJAX JSON 结果集(例如)构建分页结果时放置 Google Ad标签中间列表,然后一旦构建了列表,我就进行 Google JS 调用(3以上)。并且它允许我重建列表并根据需要多次调用 Google Ad build(上面的 3 个)(例如下一页或每页更改编号)。

Hope this helps.

希望这可以帮助。

回答by hursing

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

这有点好笑。我也很困惑。Adsense 告诉我们:

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.

,只需将整个示例代码粘贴到您要展示广告的所有位置即可。

回答by radiofrequency

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.

这些方法有效,但不适用于 https。如果您想动态放置广告并使用 https,则需要注册 DFP 广告管理系统。

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.

我在我的网站上遇到了这个问题,所以我整理了一个 npm 模块来为自己解决这个问题。希望你觉得它有用。

Use Adsense in Single Page Web Apps

在单页 Web 应用程序中使用 Adsense

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

该链接包含有关如何在单页 Web 应用程序中使用该模块的完整示例代码。

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

安装模块后,此代码将在您指定的元素中显示您的广告: ViceView.showAdsense({adslot: {slot: "myslot", sizes: "[300,100]", id:"your adsenseid"}, element: "element", adwidth: 300, adheight: 100});