I have an event handler function bound to the load event of an iframe, and I want to know if the content retrieved inside the iframe is HTML or JSON. Is there a way to achieve this?
After some research, the most feasible way I found to know which kind of content is loaded in the iframe is trough the contentType/mimeType properties of the document DOM element. We can get this property in different ways:
Inside the load handler function (way 1):
var iframedocument = $(this).contents().get(0);
var contentType = iframedocument.contentType || iframedocument.mimeType;
Inside the load handler function (way 2):
var iframedocument = this.contentDocument;
var contentType = iframedocument.contentType || iframedocument.mimeType;
Inside or outside the load handler function (way 3):
var iframe = document.getElementById('iframe_id');
var iframedocument = iframe.contentDocument;
var contentType = iframedocument.contentType || iframedocument.mimeType;
If contentType == 'application/json'
then the document loaded is JSON. If contentType == 'text/html'
then the document is HTML.
Additional notes: The idea came from Geoff Wartz's answer to this question: how to listen for returned json object with jquery The solution was based upon the proposed answer to this other question: How to get content-type from an iframe?. Finally, we have to use contentType
for Mozilla Firefox compatibility and mimeType
for IE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With