Changing the page title with AJAX Commands in Drupal

So you've loaded that new AJAX fragment using AJAX commands but you want to change the page title too?

The JavaScript

Create a new JavaScript plugin called jquery.changePageTitle.js and add it to the same pages your AJAX will be running in. Inside the JavaScript add...
/** * Changes the page title. Can be called from Drupal AJAX commands using ajax_command_invoke(). */ (function ($) { $.fn.changePageTitle = function(pageTitle) { document.title = pageTitle; }; })(jQuery);


Alongside your other AJAX Commands in your Drupal module AJAX callback add the code below replacing 'My great page title' with any string or PHP string variable you want.
// Change the page title. $ajax_commands[] = ajax_command_invoke(NULL, 'changePageTitle', array(t('My great page title')));


A good suggestion to improve consistency is to format the title including the site name in the same way Drupal does it by default.
// Change the page title. $site_title = variable_get('site_name'); $page_title = t('My Great Page'); $ajax_commands[] = ajax_command_invoke(NULL, 'changePageTitle', array($page_title . ' - ' . $site_title));