我们尝试在我们动态添加的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