views:

874

answers:

2

Hi

I've read that you cannot read the HTML of another frame if that frame resides on another domain. Is there a way to do this in Javascript? I realise this restriction is for security purposes but my use is legitimate.

Regards

Peter

A: 

Are we talking about an iFrame here? If so, could you not get the src attribute of the iFrame (jQuery?) and initiate an ajax request which would return the page, or perhaps hand the src attribute to your own script (PHP/ASP whatever) that uses CURL to glean the information you're after?

gargantaun
It's not an iframe, just a normal <frame>
A: 

Yes you can definitely read the contents of the frame using cross-domain proxy. Essentially you need to create a server-side script that requests the src URL of the frame in question. On the client side, you request this script instead of the src URL (which is on another domain and thereby subject to security restrictions within the browser), passing in the src URL as a parameter.

Server-Side Script

The following is an example with PHP using cURL.

<?php

$target = $_REQUEST['t'];
if (empty($target)) { die 'no url provided'; }

$useragent="Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$res = curl_exec($ch);
curl_close($ch);

echo $res;

?>

Client-Side Script

On your page, use the following JavaScript function to return the HTML of the target frame

    var URL = top.frames.(YOUR FRAME NAME HERE).location;

var xh = null;
if (window.XMLHttpRequest) {
  xh = new XMLHttpRequest();
} else if (window.ActiveXObject) {
  xh = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  alert("Your browser does not support XMLHTTP.");
  return false;
}

var ret = null;
xh.onreadystatechange = function() { 
  if (xh.readyState == 4 && xh.status == 200) {
    // do whatever you want with the html here
    ret = xh.responseText;
  }
}
xh.open("GET", url, false);
xh.send(null);

Let me know if this works for you.

Dustin Fineout