Mystery: How does Google do cross-domain iframe communication?
When you host Googles web search element on a page, a div is created which incorporates an iframe which points to a Google adsense ads page. However, if there are no ads for the specific query, Google somehow changes the class on YOUR domain to render the div (and iframe) invisible.
They are NOT using postMessage, as it also works in IE7. They are also not using the fragment identifier method, as no hash appears in the url. So how do they do it?
To check what I'm saying just put the following into a regular html page:
<!-- Google Custom Search Element -->
<div id="cse" style="width:100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
go开发者_开发技巧ogle.load('search', '1');
google.setOnLoadCallback(function(){
new google.search.CustomSearchControl().draw('cse');
}, true);
</script>
and then do a search for "cars" (or anything else that will definitely have ads) and then for "wzxv", which has no ads...
The script is included in your frame, so it can do to your page whatever it wants. Cross-domain restrictions only count for scripts in iframes referencing things in outer scripts from foreign domains. google.load('search', '1');
runs in your frame, owned by your domain, free of any restrictions.
The script fragment is executing in the DOM of your page, not in the ads IFrame. It creates the IFrame as a child element of the parent div in your HTML and sets its URL to load the ads, but since it's running as part of your page, it can also choose to hide the parent div instead.
Update: The script can easily run an Ajax query to the ad server and choose what to do based on the response. In fact, the script might be dumb enough to not even care about the response and just render it in the DOM and the ad server can just return another script that does the proper thing based on the result - hides the parent div
or injects the ads iframe. Heck, the ad server can directly return the proper HTML to replace the whole parent div, if necessary. All the initial script needs to know and pass along with the Ajax query is the name of its parent div, which you pass to it as a parameter.
the answer is one word lenght: jsonp
精彩评论