Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if the iframe content is html or json on load event

Tags:

json

jquery

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?

like image 630
Guillermo Gutiérrez Avatar asked Sep 20 '12 14:09

Guillermo Gutiérrez


1 Answers

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.

like image 142
Guillermo Gutiérrez Avatar answered Oct 13 '22 20:10

Guillermo Gutiérrez