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

后端 未结 3 770
無奈伤痛
無奈伤痛 2020-11-27 03:51

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

相关标签:
3条回答
  • 2020-11-27 04:24

    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);
          }
    });
    
    0 讨论(0)
  • 2020-11-27 04:38

    Crossdomain request don't work with ajax, but what you could do is write a script on your server that fetch the title of a given site.

    If you are using PHP you could use the file_get_contents and preg_match function to get the title. This guy here already provide the code for it.

    http://www.cafewebmaster.com/php-get-page-title-function

    Then in jQuery you could add this to an event or put it inside a function.

    //For the purpose of this example let's use google
    var url = "http://www.google.com";
    
    $.ajax({
      type: "POST",
      url: "./getURLTitle.php",
      data: "{url: \"" + url + "\"}",
      success: function(data) {
         //do stuff here with the result
         alert(data);
      }   
    });
    
    0 讨论(0)
  • 2020-11-27 04:42

    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);
        }
      });
    }
    
    0 讨论(0)
提交回复
热议问题