Bohdan Myslyvchuk
Bohdan Myslyvchuk

Reputation: 1817

How to print content that is returned in http response using javascript

I want to print in console content that are returned in http response. For example when I go to https://google.com and in the tab Network I can see content such as scripts, text, document, png. I want to print names of all .png files. I tried to use something like that:

function hand () {
        console.log(this.getResponseHeader('content-type'));
}
var x = new XMLHttpRequest();
x.open('GET', 'https://google.com', true);
x.onreadystatechange = hand;

x.send(); 

But it doesn't work for me. This action below is assigned for the button on me page.

Upvotes: 0

Views: 2776

Answers (1)

SK.
SK.

Reputation: 4358

Cross-origin requests simply are not allowed by default. The remote server may provide permission to your application through CORS or by supporting Ajax alternatives like JSONP.

Edited:

The only (easy) way to get cross-domain data using AJAX is to use a server side language as the proxy as Andy E noted. Here's a small sample how to implement that using jQuery:

The jQuery part:

$.ajax({
    url: 'proxy.php',
    type: 'POST',
    data: {
        address: 'http://www.google.com'
    },
    success: function(response) {
        // response now contains full HTML of google.com
    }
});

Simple as that. Just be aware of what you can or cannot do with the scraped data and be very much aware that such a proxy is a severe security hole. At least make a list of acceptable addresses and don't just blindly accept any passed address. Have a look at a decent proxy script here: PHP Simple Proxy

Upvotes: 1

Related Questions