我們嘗試在我們動態添加的iframe中顯示google廣告。在iframe中,字段「src」通常是一個網址,但我們希望使用data:text/html格式來直接使用我們的廣告代碼。它適用於簡單的JavaScript代碼,如document.write('hello world')< \ script>,但不適用於谷歌廣告代碼。 我們在HTML文件中模擬這種:在iframe中使用jquery動態顯示javascript google廣告的問題
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function resizeFrame(f) {
f.style.height = 60 + "px";
}
$(document).ready(function() {;
var htmlCode = document.createElement("div");
var head = document.getElementById('google_ad_468x60');
var myFrame = document.createElement("iframe")
myFrame.name = "childframe"
myFrame.id = "childframe"
myFrame.src = "data:text/html, " + "<script>" + "<!--\ngoogle_ad_client = \"pub-abcdef\";\ngoogle_alternate_color = \"FFFFFF\";\ngoogle_ad_width = 468;\ngoogle_ad_height = 60;\ngoogle_ad_format = \"468x60_as\";\ngoogle_ad_channel =\"\";\ngoogle_color_border = \"FFFFC6\";\ngoogle_color_bg = \"FFFFFF\";\ngoogle_color_link = \"000000\";\ngoogle_color_url = \"666666\";\ngoogle_color_text = \"333333\";\n//-->"+"<\/script>"+ "<script src = \"http://pagead2.googlesyndication.com/pagead/show_ads.js\">"+"<\/script>"
myFrame.width = "468"
myFrame.scrolling = "no"
myFrame.setAttribute('marginheight', '0px')
myFrame.setAttribute('marginwidth' , '0px')
myFrame.setAttribute('frameborder' , '0' )
head.appendChild(myFrame)
});
</script>
</head>
<body onload="resizeFrame(document.getElementById('childframe'))" bgcolor="#FFFF00">
<div>
<h1>Before Google ad</h1>
</div>
<div id="google_ad_468x60">
<-- Here is display the the Google ad --!>
</div>
<div>
<h1>After Google ad</h1>
</div>
</body>
</html>
我們沒有與Mozilla的錯誤,但Chrome的,我們有這個錯誤,在這兩種情況下沒有顯示谷歌廣告:
Unsafe JavaScript attempt to access frame with URL oursitewiththetestfile.com from frame with URL file:///home/lucas/Bureau/google_ad.html from frame with URL data:text/html, <script>google_comments</script> <script type="text/javascript" src="google_path.js"></script>. Domains, protocols and ports must match
但Firefox不顯示廣告都不是。你認爲這是出於同樣的原因嗎?而對於IE來說呢? 如果確實沒有辦法解決這個問題,我們會嘗試其他方法。 – Lucas 2010-08-13 17:10:54
很可能是由於許多網站遭到黑客利用使用JavaScript的iframe攻擊。就像大衛說的那樣,這也違背了條款和條件。無論你如何看待,iframe仍然是一個框架。 – 2010-08-14 00:27:42