How to find out if iframe content is html or json at load event

I have an event handler function associated with an iframe load event, and I want to know if the content received inside the iframe, HTML or JSON. Is there any way to achieve this?

+6
source share
1 answer

After some research in the most feasible way, I found out what content is loaded in the iframe, through the contentType / mimeType properties of the DOM document element. We can get this property in different ways:

Inside the load handler function (path 1):

var iframedocument = $(this).contents().get(0); var contentType = iframedocument.contentType || iframedocument.mimeType; 

Inside the load loader function (path 2):

 var iframedocument = this.contentDocument; var contentType = iframedocument.contentType || iframedocument.mimeType; 

Inside or outside the load handler function (path 3):

 var iframe = document.getElementById('iframe_id'); var iframedocument = iframe.contentDocument; var contentType = iframedocument.contentType || iframedocument.mimeType; 

If contentType == 'application/json' , then the loaded JSON document. If contentType == 'text/html' , then the document is HTML.

Additional notes: The idea came from Jeff Wartz to answer this question: how to listen to the returned json object with jquery . based on the proposed answer to this other question: How to get content type from iframe? . Finally, we must use contentType for compatibility with Mozilla Firefox and mimeType for IE.

+5
source

Source: https://habr.com/ru/post/925852/


All Articles