Keystone Websites

Making AdSense work with XHTML

Why won't AdSense work with true XHTML?

Google's AdSense works by using JavaScript to generate an iframe in which to dynamically serve advertisments. This is fine if the page is going to be regular HTML or non-strict versions of XHTML being served as text/html. The JavaScript generates the iframe as expected, and everything works fine and dandy. Unfortunately, for webmasters serving XHTML pages as application/xhtml+xml, the Google method doesn't work.

The main problem is the JavaScript. The function Document.Write() will not work in correctly served XML pages that are handled by an XML parser. Ian Hickson provides an explanation of why this is the case. As we have already observed, Document.Write() is used to generate the iframe; therefore, the advertisements never appear.

The second problem is the iframe itself. The element does not exist in strict flavors of XHTML, so even if the JavaScript could create it, the iframe would make the page invalid XHTML.

How can I make it work?

One way to get around these problems is to simply serve AdSense code as text/html. In order to do that, it will be necessary to create a separate web page with a MIME type of text/html and then insert it into the desired page as an object. Here is what the separate document should look like:

<?php header("Content-Type: text/html;charset=utf-8"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<html lang="en">
    <style type="text/css">
      body { margin: 0; padding: 0; }
    <script type="text/javascript">
      Normal AdSense parameters go here
    <script type="text/javascript" src=""></script>

For those webmasters using the content negotiation script to serve either application/xhtml+xml or text/html, it is possible to make use of the existing code to determine which of the two methods to employ. In the original content negotiation script, the MIME type is held in a variable called $mime. If the value of that variable is "application/xhtml+xml", the object can be included in the document. Otherwise, the standard AdSense JavaScript can be included. This script demonstrates how it can be done:

<div class="ads">
if($mime == "application/xhtml+xml") {
    print "  <object data=\"/includes/google.php\" type=\"text/html\"></object>\n";
} else {
  <script type="text/javascript">
    Normal AdSense parameters go here 
  <script type="text/javascript" src=""></script>

This solution has been tested with Internet Explorer 6.0, Firefox 0.92, and Opera 7.0.