Javascript: how to get web page content

In JS, is it possible to get the contents of a web page by assigning it to a variable? For example, why does the following toy code 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?

+4
source share
4 answers

use the server side proxy as a php page that reads the page you want and then makes ajax calls to this proxy through javascript:

 var req = new XMLHttpRequest(); req.open('GET', 'proxy.php?url=http://www.google.com', false); req.send(null); if(req.status == 200) { alert(req.responseText); } 
+6
source

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

There is also "JSONP", but this is commonly used on sites that provide some JSONP access, which most random URLs don't.

+7
source

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

+4
source

If you really need to do this, you can try using jQuery and iFrames (read more at (more info http://softwareas.com/cross-domain-communication-with-iframes ).

Alternatively, you can try with Access-Control-Allow-Origin: http: // yourdomain: 1234 / in the headers, google to share resources for different sources. This is relatively new, although not all browsers are aware of this. It also depends if you have control over the generation of other server headers and a few other things.

+2
source

Source: https://habr.com/ru/post/1343634/


All Articles