Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to fetch the content of a web page

In JS is it possible to fetch the content of a web page assigning it to a variable? For example, why the following toy code does not work?

var req = new XMLHttpRequest();
req.open('GET', 'http://www.google.com', false);
req.send(null);
if(req.status == 200)
  alert(req.responseText);

Is there a better method/code?

like image 798
tic Avatar asked Mar 14 '11 14:03

tic


2 Answers

The above does not work, because Ajax requests cannot access files/pages on other domains, due to security concerns. Typically, you can make a script using [Insert Server Side Language here] to download the requested page. Then your javascript can make a request to this page.

There is also 'JSONP', but this is typically used on sites that provide specific JSONP access, which most random URL's do not.

like image 98
Hux Avatar answered Oct 21 '22 03:10

Hux


For security reasons, you cannot use AJAX to send a request to a different domain.

like image 20
SLaks Avatar answered Oct 21 '22 03:10

SLaks