Search code examples
javascriptjqueryloadgoogle-chromehead

jQuery Can't $(...).load() the head title in Chrome


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");
});

Solution

  • 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();