8

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?

Guillermo Gutiérrez
  • 15,624
  • 15
  • 82
  • 108
  • 2
    I think regardless of what the content is, it will appear to be HTML and will be parsed as HTML. You will have to get the contents of the body tag and inspect that to see if it starts with a JSON character `{` or `[`. However, in some cases the content within the body may be wrapped in
     tags depending on what the content-type is and what browser is being used.
    – Kevin B Sep 20 '12 at 15:08
  • JSON can also be a boolean, number, null, or string. Also would want to ignore outer whitespace. – Brett Zamir Sep 20 '12 at 15:24

1 Answers1

8

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.

Community
  • 1
  • 1
Guillermo Gutiérrez
  • 15,624
  • 15
  • 82
  • 108
  • Haven't tested on IE yet, tough. I was reading somewhere that the contentType string could be different on IE. I'll check and let you know. Please comment is this answer is correct, in order to mark as accepted, correct or dispose it. – Guillermo Gutiérrez Sep 20 '12 at 20:34