Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick the title of a remote webpage [duplicate]

How I can read the title of a remote web page with javascript? Suppose the web page is:

www.google.com

I want to read the title of that page; how should I do this?

like image 605
h_a86 Avatar asked Oct 07 '22 17:10

h_a86


2 Answers

You won't be able to get this data with jQuery alone, however you can use jQuery to communicate with PHP, or some other server-side language that can do the heavy lifting for you. For instance, suppose we have the following in a PHP script on our server:

<?php # getTitle.php

    if ( $_POST["url"] ) {
        $doc = new DOMDocument();
        @$doc->loadHTML( file_get_contents( $_POST["url"] ) );
        $xpt = new DOMXPath( $doc );
        $output = $xpt->query("//title")->item(0)->nodeValue;
    } else {
        $output = "URL not provided";
    }

    echo $output;

?>

With this, we could have the following jQuery:

$.post("getTitle.php", { url:'http://example.com' }, function( data ) {
    alert(data);
});
like image 136
Sampson Avatar answered Oct 10 '22 07:10

Sampson


Getting the content of a remote page you have no control over is going to be a problem because of the same-origin-policy. For more information look here: How to get the content of a remote page with JavaScript?

like image 37
nfechner Avatar answered Oct 10 '22 07:10

nfechner