0

A user on my website will enter a url (a public page on another domain) in a textbox. I want to fetch the HTML source code that page as a string. How to do this using client side scripting ?

Following is what I did to load url. But not able to figure out how to fetch html.

<!DOCTYPE html>
<head>
<script>
function myFunction()
{
document.getElementById("site").src=document.getElementById("web").value;
}
</script>
</head>
<body> 
<input id="web" type="text" name="user">
<input type="submit" value="Submit"  onclick="myFunction()"> <br/>
<iframe id="site" src="" width="1200" height="1200"></iframe>

</body>
</html>
Ashni Goyal
  • 819
  • 3
  • 10
  • 20

2 Answers2

3

Create a script on your server, and call it using AJAX, then use cURL like so:

 $ch = curl_init();
 $timeout = 10;
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

 $data = curl_exec($ch);

 curl_close($ch);

And $data will contain the contents.

Tom Walters
  • 15,366
  • 7
  • 57
  • 74
2

I'm afraid the javascript on your website can't access the source code of other websites due to the Same Origin Policy. This is to prevent Cross Site Scripting attacks. For example, if the user was logged into their email account, the Same Origin Policy prevents other websites, open in the same browser, from trying to access your email.

Your best bet is to:

  • Send the url to your application server via AJAX
  • Perform a HTTP GET from your application server (in Java / PHP etc)
  • Reply to the AJAX request with the text of the other website
  • Then show the source code to your user