title: Magento: Prepend block to Mage Head Block using controller_action_postdispatch event observer
body: <p>I am trying to use a custom event observer to observe the <code>controller_action_postdispatch</code> event and modify the response body directly by replacing opening head tag with + my custom block content. It is important that I make sure that it is an actual HTML page response, and not JSON or partial HTML in the case of an AJAX request. I would like to use the <code>controller_action_layout_render_before</code> event to determine that the head block is present, set a flag, which the previously mentioned observer method will check before modifying the response.</p>
  
  <p>The use case is to safely prepend my custom block inside the head tag of every page, taking priority order over other head content such as meta tags, and script tags.</p>
  
  <p>This is where I am at right now (not far, got a little lost)...</p>
  
  <h2>config.xml</h2>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;config&gt;
      ...
      &lt;global&gt;
          ...
          &lt;events&gt;
              &lt;controller_action_postdispatch&gt;
                  &lt;observers&gt;
                      &lt;intercept_response&gt;
                          &lt;class&gt;module/observer&lt;/class&gt;
                          &lt;method&gt;interceptResponse&lt;/method&gt;
                      &lt;/intercept_response&gt;
                  &lt;/observers&gt;
              &lt;/controller_action_postdispatch&gt;
              &lt;controller_action_layout_render_before&gt;
                  &lt;observers&gt;
                      &lt;check_response&gt;
                          &lt;class&gt;module/observer&lt;/class&gt;
                          &lt;method&gt;checkResponse&lt;/method&gt;
                      &lt;/check_response&gt;
                  &lt;/observers&gt;
              &lt;/controller_action_layout_render_before&gt;
          &lt;/events&gt;
      &lt;/global&gt;
      ...
  &lt;/config&gt;
  </code></pre>
  
  <h2>Model/Observer.php</h2>
  
  <pre><code>class My_Module_Model_Observer {
  
      protected $_isHead = FALSE;
  
      public function checkResponse() {
          if ( Mage::app()-&gt;getLayout()-&gt;getBlock('head')) {
              $_isHead = true;
          }
      }
  
      public function interceptResponse(Varien_Event_Observer $observer) {
          $block = $observer-&gt;getBlock();
      }
  
  }
  </code></pre>