views:

176

answers:

2

I need to get the title of a remote page by URL. The code works in FFX, but not chrome. Anyone have any ideas?

$(document).ready(function(){
    $("title").remove();
    $("head").load("http://www.latentmotion.com title");
});
+2  A: 

Here, this works in all browsers

$.get("http://www.latentmotion.com", function(response){
     alert((/<title>(.*?)<\/title>/m).exec(response)[1]);
  });

You can test it here http://jsfiddle.net/N7D5r/

And if you want to avoid jQuery altogether

var getXhr = (function () {
    if ("XMLHttpRequest" in window) {
        return function () {
            return new XMLHttpRequest();
        };
    }
    else {
        var item = (function () {
            var list = ["Microsoft", "Msxml2", "Msxml3"],
                i = list.length;
            while (i--) {
                try {
                    item = list[i] + ".XMLHTTP";
                    var obj = new ActiveXObject(item);
                    return item;
                }
                catch (e) {}
            }
        }());
        return function () {
            return new ActiveXObject(item);
        };
    }
}());

var req = getXhr();
req.open("GET", "http://www.latentmotion.com", true);
req.onreadystatechange = function () {
    if (req.readyState == 4) {
        if (req.status >= 200 && req.status < 300) {
            // here you retrieve the title
            var title = (/<title>(.*?)<\/title>/m).exec(req.responseText)[1];
            alert(title);
        }
        req.onreadystatechange = null;
        delete req.onreadystatechange;
    }
};
req.send();
Sean Kinsey
+1 for a working solution - side note: need to remove an extra paren on `if ("XMLHttpRequest" in window)) {` up top to make it valid.
Nick Craver
Thanks, it has been fixed
Sean Kinsey
Thanks! But if a page doesn't have a title, this throws an error. Any ideas?
Matrym
I've created a followup SO questions here: http://stackoverflow.com/questions/2915795/javascript-jquery-geturl-title-parsing-not-working
Matrym
A: 

Thanks, but it's not work on chrome. and IE is ok

Vincent