使用 JavaScript 动态插入 Adsense

新手上路,请多包涵

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

基本上,用户插入我的脚本,让我们称之为 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>

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

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

原文由 Oscar Godson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
1 个回答

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

要使其正常工作,您需要覆盖 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>

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

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

原文由 Johnny Oshika 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题