I'm having trouble trying to display a PDF preview within an iframe
tag. I have a page that contains some iframe
s to display a PDF file in the page, the problem is sometimes the PDF is not present in the source URL, so the iframe
shows an XML error stating BlobNotFound
. I want to hide iframe
if that error is returned in the source code of iframe
.
I tried the following JavaScript script:
<script> const myIframe = document.getElementById('myFrame1'); fetch('example.xml') .then(response => { if (!response.ok) { throw new Error('XML file not found'); } return response.text(); }) .then(xmlString => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, "text/xml"); // check for errors in the XML content const error = xmlDoc.getElementsByTagName("parsererror"); if (error.length > 0) { myIframe.style.display = 'none'; // hide the iframe if there is an error } }) .catch(error => { console.error(error); myIframe.style.display = 'none'; // hide the iframe if there is an error }); </script>
This code works, but only if you specify the iframe
tag by ID, and I want to rewrite this code to check all iframe
at once.
I also tried the following code:
<script> const iframes = document.getElementsByTagName('iframe'); for (let i = 0; i < iframes.length; i++) { const iframe = iframes[i]; fetch(iframe.src) .then(response => { if (!response.ok) { throw new Error('XML file not found'); } return response.text(); }) .then(xmlString => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, "text/xml"); // check for errors in the XML content const error = xmlDoc.getElementsByTagName("parsererror"); if (error.length > 0) { iframe.style.display = 'none'; // hide the iframe if there is an error } }) .catch(error => { console.error(error); iframe.style.display = 'none'; // hide the iframe if there is an error }); } </script>
This code should work, but somehow it hides all iframe
s even though it has no errors.
P.S.\ This is an XML error for any iframe
that cannot display the PDF.
<?xml version="1.0" encoding="utf-8"?> <Error> <Code>BlobNotFound</Code> <Message> The specified blob does not exist. RequestId:xxxxxxxx Time:timestamp </Message> </Error>
You can try this!
Please tell me if it works.