I see that this question has been asked many times here. Some of the solutions partially work. This is the scenario. I need to load an iframe which has a pdf using <embed>
. There are chances the PDF is not found and I will be showing error page within iFrame.
Once the iframe is loaded, I look for <embed>
tag using
$('#iframe').contents().find('embed')
I tried using $('#iframe').load()
. This works in Firefox, Chrome but not IE.
Also tried using $('#iframe').ready()
. This works in IE, however,
$('#iframe').contents().find('embed')
doesn't work.
Can someone please help out ?
EDIT : IE Version : 7 or 8. Same origin policy is respected.
Which version of jquery and IE are you using? I made a small test setup like follows and it works just fine...
Main HTML
<html>
<head>
<title>TEST</title>
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('iframe').ready(function(){
var tag = $('#iframe').contents().find('embed');
alert(tag.attr('src'));
});
</script>
</head>
<body>
<iframe id="iframe" src="pdf.html">
</body>
</html>
Iframe HTML
<html>
<body>
<embed src="mypdf.pdf"/>
</body>
</html>
Tested on Windows 7, IE9.
$('#iframe').load
or <iframe onload="">
doesn't work. Looks like in IE iframe contents for PDF cannot be accessed. So to track iFrame load, following code can be used.
$(window).load(function() {
try {
var s = window.frames[ "iframeName" ].document.body.childNodes[0].innerHTML;
if(s.indexOf('My error message') > 0) {
alert('Error');
} else {
alert('PDF');
}
} catch (err) {
if($.trim(err.message) != 'Access is denied.') {
alert('PDF');
} else {
alert('Error');
}
}
});
So in case a error message 'My error message' is found then it is the custom-designed-error page which has the message, else it is the PDF.
The above solution is for IE7 & IE8. For the rest of the browsers, following can be checked
$('#iframe').contents().find('embed').attr('src')
Not a straight forward solution. But works for me.