How to get iframe response headers? - javascript

Is there a way to get response headers of an iframe onload?
I have already googled it, but really I could not find something useful about it!

Not really. If the iframe is on the same domain you can access its document object which contains some useful information such as document.referrer, but you cannot intercept the full HTTP headers without making an Ajax request for the URL. This would mean requesting the URL again. e.g:
$.ajax( { url: $(#myFrame).attr('src'), success: function(r,x){
console.log( x.getResponseHeader('SomeHeader') );
} } );
This will only work if the iframe src is in the same domain as the calling script.

If you have control on the loaded iframe resource you can dump the header content on a postMessage request to the main window.

Related

Get a file through AJAX with JQuery

I looked for an answer to my problem everywhere but I didn't found what I want to know.
Here is what I want to do:
I have an url of an image, pdf or html page from the same domain and from other domains too. Is it possible to "download" them with AJAX?
But I don't want to have them physically on my server or anywhere else, I just want to use them directly on my website without having to upload them again (to save time).
I'm also having some troubles doing "XMLHttpRequest.getAllResponseHeaders()" when the content comes from an other domain. I tried with multiples url. I received nothing: "". Is it normal?
Thank you for your help ! :)
Unfortunately it is impossible to make AJAX requests for resources on domains external to the website's host domain, edit: unless they implement a workaround, like CORS or JSONP. I recommend doing some reading on Cross Origin Resource Sharing for more details.
As for resources on the same domain, you'd be storing those on your server anyway - you'd have to, in fact, because by its very nature it would be a part of your site. If you describe what you're trying to implement specifically (perhaps post a jsfiddle with your code), we could find a solution to your specific use case. Hope this helps.
[...] image, pdf or html page [...]
The types of these requests are very different. What you mean with 'download' is a little ambigious. If you're requesting a file via AJAX, this loads the value into a variable. It doesn't save the file to your computer.
[...] I received nothing: "" Is it normal? [...]
Yes, if the remote server isn't the same as you're currently on (also the same port) and also doesn't support CORS (cross-domain requests), the result will be blank.
If it's not possible to alter the remote server's cross-domain policies [and you have the permission to use their services], you could write a PHP script on your server that acts as a proxy. But don't forget to secure it to prevent mis-use. Also keep in mind that such a script can raise your traffic dramatically, so this should only be "Plan B".
You certainly can fetch images and html pages with AJAX and display them on your webpages.
The issues you are having with the xmlHttpRequest.GetAllResponseHeaders is most likely caused by the same origin policy. The browser prohibits you from interacting with the loaded data from another domain.
The server you are fetching the data from has to explicitly indicate that it allows your domain to fetch and display his resources by setting the Access-Control-Allow-Origin response header to that of your domain.
A way arround this is by using a proxy and setting the header yourself.
The following boilerplate code ( basically taken from the jquery api page ) loads your gravatar image ( delivered in png format ) from the stackoverflow website into a callback parameter. As others have noted, the same origin policy applies to ajax requests ( The sample code therefore can onlybe successfully run from the stackoverflow site context, eg. by opening a js console on this page ).
$.ajax({
method: "GET"
, url: "https://www.gravatar.com/avatar/d85e0ad5243245aabe2d34a3c9a296a9?s=32&d=identicon&r=PG&f=1"
, cache: false
, beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Length of data:", data.length );
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});

slideshare oembed api and Access-Control-Allow-Origin

I'd like to embed a slideshare iframe based on its URL. http://www.slideshare.net/developers/oembed says I should be able to get a JSON object about the resource and within that is the embed code to use. E.g. if I open
Reference Link
in the browser, I get JSON. If I open the same via jquery
$.getJSON('http://www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/lyndadotcom/code-drivesworld12&format=json', function (obj) { console.log(obj) });
then I get
XMLHttpRequest cannot load http://www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/lyndadotcom/code-drivesworld12&format=json&callback=myFunction. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Ideally I'd like to also control slideshare from an external link - which this page - http://www.slideshare.net/developers - says is possible if you follow the SlideShare Player API - which is a 404 page.
Googling for slideshare developer just links me to many shared slideshows, not actual help that exists or works ... grrr
When you try to load JSON from another domain, it fails because there is a domain boundary you can not cross.To avoid this, you have to use JSON with Padding. JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. Try this following code mate.Hope this might help you. :)
$.ajax({
type: "GET",
url: 'http://www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/lyndadotcom/code-drivesworld12&format=jsonp',
dataType: 'jsonp',
success: function (data) {
$('.dynamic').html(data.html);
}
});
Fiddle here

Extracting HTTP Headers from HTTP 300-code responses using Ajax

I am performing an Ajax request to a server that accepts cross-domain requests but for which I have no control over the server code. My desire is to extract an HTTP Link header from the response. As an example:
$.ajax({
url: theURL
}).done(function(data,textStatus,xhr){});
hits a server that responds with the following (as observable when the URL is queried with curl):
HTTP/1.1 302 Found
Link: <http://thedataIwant.com>;rel="foo"
Location: http://someothersite.com
The browser follows the HTTP 3XX code and I get the contents of the HTTP headers from http://someothersite.com in the done() handler; however, I would like to first extract the contents of the Link header for the initial HTTP response with the 3XX code.
How do I go about extracting the contents of the HTTP Link header from an HTTP response with 3XX status code?
I was intrigued by your question and though to search around for a solution. Unfortunately, there isn't a direct one. According to all posts I read so far (How to manage a redirect request after a jQuery Ajax call and many similar ones) you can't simply catch the 301 redirect because browsers usually fetch the content and give the endpoint to the user, which is why you get the 200 status code instead of the 302. As a workaround, people are suggesting to use a custom header. When you receive the header after doing an ajax request, you could do your own manipulation i.e. save the Link header and then make a second ajax request to get the content from MyRedirectLocationHeader: http://someothersite.com.
The code would look something similar to this:
$.ajax({
url: theURL,
success: function(response, status, xhr) {
var link = xhr.getResponseHeader('Link');
if(link != null) {
// my second ajax request to the link in the MyRedirectLocationHeader
}
}
});
This is an awful looking hack, but that's the only workaround I've found so far which actually works. Another way might be for you to create a proxy script/service using PHP,Java or another similar language, that would get the request without following the redirects and would print out only the Link and Location as JSON or XML. Afterwards your javascript would parse the response and proceed to someothersite.com
What is interesting to me, though, is that the official jQuery ajax documentation page implies there is support for the 3xx redirects (near the documentation for the statusCode) but that doesn't seem to be working.

jQuery.get() fails with full url

var url = "/example/somelink";
jQuery.get( url, params, callback); //works fine
var url = "http://www.yahoo.com";
jQuery.get( url, params, callback); //fails!
when I give the full URL of a site, get() fails...any idea why this is happening?
Thanks
You can't access a remote domain like this, only your own domain. The difference is the domain, not the full vs relative URL.
It's the same origin policy that's blocking you here, you have to use JSONP to get data directly or proxy the request through your own domain.
If by "fails", you mean that you're unable to access the HTML you hoped to receive, this is prevented by the browser for security reasons.
You can manipulate the response only if it comes from the same domain from which the request is sent.

set an iframe source without loading new content

Is there any way to set the src attribute of an iframe without the iframe generating an http request? If not, is there a way to format the request headers before the request is sent?
edit: I just need the src to match the path of a cookie, but I don't ever want that cookie sent to the server. See my comments on this question.
No there is not a way to do this.

Categories