上次發了一篇 jQuery|在痞客邦部落格文章內置入Google Adsense(1)(透過iframe),雖然 google 准許我們將廣告放在內置框架中,但總覺得怪怪的,主要還是把怕 google adsense 放在框架頁中會抓不到網頁的關鍵字。而 google 的 show_ads.js 也是利用框架頁的方式來放廣告的,如果我們也使用框架頁,它就被放在兩層框架中了。這幾天我研究了一下,還是沒辦法單純使用 jQuery 的 append() 來置入 show_ads.js,直接 append show_ads.js 網頁會顯示一片空白。用 firebug 觀察,發現網頁除了會在 head 裡置入一個 window.google_render_ad() 外,就什麼都沒有了:

gads_err.jpg

  但奇怪的是,透過 Javascript 最原始的寫法 innerHTML 卻可以成功地將 show_ads.js 載入,我想破頭都想不出是什麼原因…。推測可能是 google 的 show_ads.js 在抓取網頁內容決定如何將廣告做顯示的這個動作可能跟 jQuery 在執行 append() 的動作有衝突。

  雖然我們無法使用 append() 將 show_ads.js 載入 .article-content,但我們可以利用 innerHTML 把 show_ads.js 載入 #article-content。疑~?痞客邦的文章內容區塊不是 .article-content 嗎?別忘了!jQuery 有個方法叫做 attr() ,我們可以將 .article-content 這個 div 再加上一個 id 的屬性,這樣就可以使用 InnerHTML 在 div id 中置入 show_ads.js 了:

<script type="text/javascript">
google_ad_client = "pub-xxxxxxxxxxxxxxxx";
google_ad_slot = "xxxxxxxxxx";
google_ad_width = 468;
google_ad_height = 60;
</script>

<div id="none_ads" style="display:none">
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<script type="text/javascript">
//把div.article-content 再加上一個 id = article-content 的屬性
jQuery(".article-content").attr("id", "article-content");
c = document.getElementById("article-content");
if (c != null) {
  div = document.getElementById("none_ads");
  c.innerHTML = c.innerHTML + div.innerHTML;
}
</script>
參考資料:(原創) 如何在Blog內任意處動態產生Google AdSense廣告? (Web) (CSS) (JavaScript)
arrow
arrow
    全站熱搜

    bshadow 發表在 痞客邦 留言(0) 人氣()