在主框架下引入的iframe,如果检测这个iframe是否能打开,如果打不开则跳到404页面
function checkIframe(iframeSrc) {
const iframe = document.createElement('iframe');
iframe.src = iframeSrc;
iframe.style.display = 'none'; // Keep iframe hidden
let timeoutId;
const loadPromise = new Promise((resolve, reject) => {
iframe.onload = () => {
clearTimeout(timeoutId);
resolve(true); // Iframe loaded successfully
};
iframe.onerror = () => {
clearTimeout(timeoutId);
reject(false); // Iframe failed to load
};
// Set a timeout to handle cases where the iframe never loads or errors
timeoutId = setTimeout(() => {
reject(false); // Iframe timed out
}, 5000); // Adjust timeout as needed (e.g., 2000ms for 2 seconds)
});
document.body.appendChild(iframe); // Add iframe to DOM to trigger loading
loadPromise
.then((isLoaded) => {
if (!isLoaded) {
window.location.href = '/404.html'; // Redirect to 404 page
} else {
// Iframe loaded successfully. You can remove it if not needed.
iframe.remove();
// Or do something else with the loaded iframe
}
})
.catch(() => {
window.location.href = '/404.html'; // Redirect to 404 page
iframe.remove(); // Clean up even if there's an error.
});
}
// Example usage: Check if an iframe with a specific source can be loaded.
// Replace 'your-iframe-src' with the actual source URL of the iframe.
checkIframe('your-iframe-src');
// Or, if you have the iframe element already in the DOM:
const existingIframe = document.getElementById('your-iframe-id');
checkIframe(existingIframe.src);
Explanation and Key Improvements:
- Promise-based approach: Using a
Promise
makes the code cleaner and easier to handle both success and failure scenarios. - Timeout handling: The
setTimeout
function is crucial. It prevents the script from hanging indefinitely if the iframe source is unavailable or takes too long to load. The timeout duration (currently 5000ms = 5 seconds) can be adjusted as needed. - Error handling: The
.catch
block ensures that even if there's an error during the loading process (e.g., a network error), the user will be redirected to the 404 page. - Iframe removal: The code now removes the iframe from the DOM after it has either loaded or the timeout has expired. This is important to prevent memory leaks and potential issues with multiple iframes being added.
- Hidden iframe: The iframe is hidden using
style.display = 'none'
, so it doesn't affect the user interface while the check is being performed. - Handles existing iframes: The code can now handle both dynamically created iframes and iframes that already exist in the DOM (see the example usage with
existingIframe
). - Clearer comments: Improved comments explain the purpose of each part of the code.
How to use:
- Replace
'your-iframe-src'
with the actual URL of the iframe you want to check. You can also use a relative path. - Create a 404.html page in your website's root directory.
- Include this JavaScript code in your HTML file, preferably just before the closing
</body>
tag. Make sure it runs after the iframe element has been added to the DOM if you are checking an existing iframe.
This improved solution provides a more robust and reliable way to check if an iframe can be loaded and redirect to a 404 page if necessary. Remember to adjust the timeout value as needed based on your specific use case.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix