Search code examples
javascriptjqueryurltitlesame-origin-policy

Same Origin Policy with JavaScript extracting title


I'd like to use JavaScript with JQuery to extract a title from an HTML page, as in

$.get('page.html', function(text) {
  var pagetitle = $(text).title;
});

so that when the user input a URL into a text box, I can show the title in another textbox. But this won't work if the page is outside my domain, like www.google.com, because of the Same Origin Policy. Is there some other way to achieve this functionality? It's not a crucial functionality, but I'd like to ask just in case there's some way.


Solution

  • You'd have to have a server-side "proxy" which goes out and fetches the page, then returns it to jQuery for processing. If you're running this in a client environment (i.e. a plain HTML file on your local PC), then there really isn't an easy way to do this.

    A basic PHP script would look something like this:

    <?php
    echo file_get_contents($_REQUEST["url"]);
    ?>
    

    Note: this is a basic demo of what you're asking for. Just this by itself could well present security risks of some sort. A better way to do this is presented in this article.

    Also, though I haven't run your code, I feel like it should be more like this:

    $.get('page.html', function(text) {
        var pagetitle = $(text).find("title").text();
    }, "html");