diracdeltafunk
diracdeltafunk

Reputation: 1184

How to get the content of an external page as a javascript object?

So I know there are many ways to get the content of an external page as a string (for example with PHP) but is there a way to get it as a javascript/JSON object (a DOM Window object for example) so I can easily manipulate it? I was thinking perhaps working with iframes, but as always, the same origin policy applies. I feel that this may not be possible by design, but I am interested to try. Does anyone have a creative solution for this? I don't want to use flash or sliverlight (because of iPhone issues).

Upvotes: 2

Views: 2261

Answers (3)

bezmax
bezmax

Reputation: 26132

The only way to do it is through your server. Expose some AJAX method for the purpose of fetching external webpages (or one specific webpage) and let the server do the job instead of the client.

Added:

For PHP, you can do it this way:

  1. Create file getremotecontent.php
  2. Using file_get_contents fetch the URL you desire (in PHP file):

    $pagestr = file_get_contents('http://www.example.com/');
    
  3. Using json_encode encode the resulting string into JSON object.

    $pagejson = json_encode($pagestr);
    
  4. Next, send the appropriate headers:

    header('Cache-Control: no-cache, must-revalidate');
    header('Content-type: application/json; charset=utf-8');
    
  5. Finally, send the content of the encoded string:

    print $pagejson;
    
  6. In Javascript, make a Ajax (XHR) request to getremotecontent.php. Server will get you your webpage, encode it into JSON format and give it back for you to process on the client side.

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328604

No. For security reasons, you can only access pages from the same domain as the one which runs your JavaScript. This is called same origin policy.

Upvotes: 1

Alan Whitelaw
Alan Whitelaw

Reputation: 16890

This is possible with jQuery

http://api.jquery.com/load/

Upvotes: -1

Related Questions