乐闻世界logo
搜索文章和话题

How to detect an error 404 in an iframe?

3个答案

1
2
3

How to detect 404 errors within an iframe? Embedding <iframe> in HTML is commonly used to load another page within the current page. However, when the target page is unavailable or encounters issues (such as returning a 404 error), browsers do not provide a direct method to detect such errors by default. Nevertheless, we can employ techniques to detect 404 errors within the <iframe>.

One possible approach involves using JavaScript to detect loading errors within the <iframe>:

javascript
window.addEventListener('load', function() { var iframe = document.getElementById('my-iframe'); iframe.addEventListener('load', function() { try { // Attempting to access the iframe's content may fail due to the Same-Origin Policy var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Verify proper page loading by checking for the existence of the body if (iframeDoc.body && iframeDoc.body.innerHTML.trim().length > 0) { // Page loaded successfully } else { // Page failed to load properly, possibly indicating a 404 or other error console.error('Iframe load failed.'); } } catch (e) { // Same-Origin Policy error; unable to access iframe content console.error('Cross-origin iframe detected. Unable to read the contents.'); } }); // Attempt to load the page by setting the iframe's src attribute iframe.src = 'https://example.com/some-page.html'; });

Note that due to the browser's Same-Origin Policy, if the page loaded in the <iframe> originates from a different origin, JavaScript cannot access the iframe's content. Consequently, the above code will not function in cross-origin scenarios and will trigger errors in the console.

If you have control over the content page within the <iframe>, consider implementing JavaScript to send a message back to the parent page, confirming successful loading. This can be achieved using the window.postMessage method. The parent page listens for these messages; if it does not receive the expected message, it can assume the page failed to load (possibly due to a 404 or other error).

Here is a simple example using window.postMessage:

Parent page:

javascript
window.addEventListener('message', function(event) { // Verify the message originates from the expected iframe page if (event.origin === 'https://example.com') { if (event.data === 'loadSuccess') { console.log('iframe loaded successfully'); } } }, false); var iframe = document.getElementById('my-iframe'); iframe.src = 'https://example.com/some-page.html';

Iframe content page:

javascript
// Send a message to the parent page upon content page load window.onload = function() { // Send message to the parent page window.parent.postMessage('loadSuccess', '*'); };

Ensure that in production environments, replace '*' with the parent page's origin (e.g., 'https://parent-website.com') to enhance security. This prevents messages from being sent to arbitrary recipients.

2024年6月29日 12:07 回复

Here's an example of your HTML:

html
<html> <head></head> <body> <iframe id="iframe"></iframe> </body> </html>

There are two scenarios:

  1. Your iframe's src is on the same domain as your page.

    Example: page URL www.example.com and iframe's src www.example.com/iframe

    You can use a jQuery AJAX request to check if the resource is available.

    javascript
    $(function() { $.ajax({ type: "HEAD", async: true, url: "www.example.com/iframe" }) .success(function() { "#iframe".attr("src", "www.example.com/iframe"); }) .error(function() { // Handle the error, perhaps by providing a failover URL }) });
  2. Your iframe's src is not on the same domain as your page.

    Example: Page URL www.example.com and iframe's src www.otherdomain.com/iframe

    Now, due to CORS policy, browsers will not allow you to make cross-site requests from JavaScript code. The solution is to make a JSONP request.

    javascript
    $(function() { $.ajax({ url: "www.otherdomain.com/iframe", dataType: "jsonp", timeout: 5000, success: function() { "#iframe".attr("src", "www.otherdomain.com/iframe"); }, error: function(parsedjson) { if (parsedjson.status == "200") { "#iframe".attr("src", "www.otherdomain.com/iframe"); } else { // Handle error } } }); });
2024年6月29日 12:07 回复

状态仅存在于响应标头中。

404 页面正在处理HTTP 状态代码,该状态代码仅包含在服务器发送到浏览器的响应中,但不包含在javascript 可以访问的实际 DOMwindow和对象中。document这意味着,虽然您当然可以收集状态代码并采取适当的操作,但您只能在 javascript 接收响应时执行此操作,例如使用 jQuery.ajax () 请求XmlHttRequest 来加载“iframe”

希望404页面遵循404标准。

如果上述方法不可行,则唯一的其他可能性可能是检查标题和/或 H 标签中的“ 404 ”。虽然这肯定不太理想(我很想看到“404,找不到电影,电影。”),但这是您唯一的其他选择。

shell
$('#iframe').load(function (e) { var iframe = $("#iframe")[0]; if ( iframe.innerHTML() ) { // get and check the Title (and H tags if you want) var ifTitle = iframe.contentDocument.title; if ( ifTitle.indexOf("404")>=0 ) { // we have a winner! probably a 404 page! } } else { // didn't load } });
2024年6月29日 12:07 回复

你的答案