我在尝试在 iframe 标记内显示 PDF 预览时遇到问题。我有一个页面包含一些 iframes 以在页面中显示 PDF 文件,问题是有时源 URL 中不存在 PDF,因此 iframe 显示 XML 错误,指出 BlobNotFound。如果在 iframe 的源代码中返回该错误,我想隐藏 iframe。
我尝试过下面的 JavaScript 脚本:
<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>
此代码有效,但前提是您通过 ID 指定 iframe 标记,并且我想重写此代码以一次检查所有 iframe。
我也尝试过下面的代码:
<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>
这段代码应该可以工作,但不知何故它隐藏了所有 iframes 即使它没有错误。
P.S.\ 这是任何无法显示 PDF 的 iframe 的 XML 错误。
<?xml version="1.0" encoding="utf-8"?>
<Error>
<Code>BlobNotFound</Code>
<Message>
The specified blob does not exist.
RequestId:xxxxxxxx
Time:timestamp
</Message>
</Error> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你可以试试这个!
<!DOCTYPE html> <html> <head> <title>Hide Iframes with XML Error</title> </head> <body> <iframe src="path/to/pdf1.pdf"></iframe> <iframe src="path/to/pdf2.pdf"></iframe> <iframe src="path/to/nonexistent.pdf"></iframe> <iframe src="path/to/pdf3.pdf"></iframe> <script> var iframes = document.getElementsByTagName('iframe'); for (var i = 0; i < iframes.length; i++) { var iframe = iframes[i]; iframe.contentWindow.addEventListener('error', function(event) { if (event.message === 'BlobNotFound') { // Hide all iframes if any one of them has an XML error for (var j = 0; j < iframes.length; j++) { iframes[j].style.display = 'none'; } } }); } </script> </body> </html>请告诉我它是否有效。