Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get source code from a webpage?

Tags:

javascript

php

How can we get the source code of a webpage from a webpage in php and/or javascript?

like image 900
user1365010 Avatar asked Dec 12 '22 01:12

user1365010


2 Answers

In Javascript without using unnecessary frameworks (in the example api.codetabs.com is a proxy to bypass Cross-Origin Resource Sharing):

fetch('https://api.codetabs.com/v1/proxy?quest=google.com').then((response) => response.text()).then((text) => console.log(text));
like image 61
D.Snap Avatar answered Dec 21 '22 08:12

D.Snap


Thanks to:

  • @PLB
  • @Shadow Wizard
  • Getting the source code of an iframe
  • http://www.frihost.com/forums/vt-32602.html
  • @Matt Coughlin.

First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).

In PHP, this is how you do it :

file_get_contents($theUrl);

In javascript, there is three ways :

Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/

var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);

Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/

var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
    alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);

Thirdly, by jQuery : http://jsfiddle.net/edggD/2/

$.get('../edggD',function(data)//Remember, same domain
{
    alert(data);
});
like image 29
Mageek Avatar answered Dec 21 '22 07:12

Mageek