Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the title of a webpage given the url (an external url) using JQuery/JS

I am a newbie, so excuse me if this is a silly question ..

So what I was trying is to get the title of a URL using JQuery/JS. I dont want to load the content of the url and then parse tags in it.

Let me be more clear, I have a set of urls, say 20 for which I want to display the titles .. the urls i am referring to are not the current urls, so I cant use js document.title ..

so i want to do something of the form SOMEFUNC.title(URL) and get its title. Is there any such function?

like image 606
user1014390 Avatar asked Oct 26 '11 11:10

user1014390


2 Answers

Something like this should work:

$.ajax({
  url: externalUrl,
  async: true,
  success: function(data) {
    var matches = data.match(/<title>(.*?)<\/title>/);
    alert(matches[0]);
  }   
});

TheSuperTramp is correct, above will not work if externalUrl is outside of your domain. Instead create this php file get_external_content.php:

<?php
function file_get_contents_curl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$url = $_REQUEST["url"];
$html = file_get_contents_curl($url);

preg_match('/<title>(.+)<\/title>/',$html,$matches);
$title = $matches[1];

echo  json_encode(array("url" => $url, "title" => $title));

then in javascript:

function getTitle(externalUrl){
  var proxyurl = "http://localhost/get_external_content.php?url=" + externalUrl;
  $.ajax({
    url: proxyurl,
    async: true,
    success: function(response) {
      alert(response);
    },   
    error: function(e) {
      alert("error! " + e);
    }
  });
}
like image 183
uncreative Avatar answered Sep 18 '22 22:09

uncreative


You can also get the title of any webpage using this API

http://textance.herokuapp.com/title/

$.ajax({
      url: "http://textance.herokuapp.com/title/www.bbc.co.uk",
      complete: function(data) {
        alert(data.responseText);
      }
});
like image 30
Durgesh Avatar answered Sep 21 '22 22:09

Durgesh