Saturday, January 17, 2009

Fetching Page Titles using jquery Ajax - RSH page title implementation

How to fetch Titles of HTML pages from URLs using jquery-ajax


There are many cases when we want to know the Titles of HTML pages without actually visiting them. One particular instance of this problem is when we are using RSH (Really Simple History). This is because with RSH and/or Ajax page navigation, the page never reloads and so browser never changes the title of the page either. In this case, we need to programmatically fetch the titles and update the current page title with the fetched one.

Unfortunately, there is no really clean way of fetching a page title through javascript other then fetching the whole page through Ajax and then parsing the HTML to extract the title. This is the technique that I'm going to elaborate on in this article.

Using jquery, the lines of code required is deceptively simple though! You can get the whole thing done, from fetching the HTML and updating the current title, in just about 2-3 lines of code! Below is how -

$.get('yourlink.com', function(data){
document.title = data.toString().substring(data.toString().indexOf("<title", 0) + 7, data.toString().indexOf("</title", 0));
});

Yes, that was it! I used jquery's $.get(link, callback) method that gets the contents of the link (passed as the first argument) through Ajax and then I just extracted the page title from the fetched HTML by javascript String.substring(indexStart, indexEnd) method. You'll also notice that the $.get()'s callback has the argument called "data" that contains the returned or fetched HTML for the provided link. It works fine performance wise as well as we are not really doing any resource intensive operations on the fetched HTML (like displaying it somewhere, for example)

Another thing I'd like to note is the use of String.substring() method. It's not the cleanest way of doing it and a more "correct" way is to use javascript regular expression as in the below example -

document.title = data.toString().match(/\<title\>(*)\<\/title/);

But the problem is that javascript has some limitations when it comes to regular expressions and the above code throws a invalid quantifier error. So, I decided to use the substring method in this case.

To find how to use RSH (Really Simple History) to solve Ajax back button problem, click - Implementing RSH (Really Simple History) for Ajax driven pages

To learn how to call webservices easily using jquery and JSON, click - Calling Webservices with jquery's Ajax and JSON without using ASP.NET's ScriptManager

1 comment:

  1. Hi Ambi

    this is a good script!

    One question, please.

    How can i assign the title fetched with $.get into a element, for example $('#inputfield') ?

    Thank's

    ReplyDelete