乐闻世界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 回复

The status code only exists in the response headers.

404 error pages are associated with HTTP status codes, which are exclusively included in the server's response sent to the browser but not accessible in the actual DOM window and document objects that JavaScript can interact with. This means that while you can certainly collect the status code and take appropriate actions, you can only do this when JavaScript receives the response—such as using jQuery.ajax requests as demonstrated here or XMLHttpRequest to load an 'iframe'.

Ideally, 404 pages should follow standard 404 page conventions.

If the above methods are not feasible, the only other possibility might be to check the title and/or H tags for '404'. Although this is certainly not ideal (I'd really prefer to see '404, movie not found, movie.'), it remains your only other option.

javascript
$('#iframe').load(function (e) { var iframe = $('#iframe')[0]; if (iframe.innerHTML) { // Get and check the title (and H tags if desired) var ifTitle = iframe.contentDocument.title; if (ifTitle.indexOf('404') >= 0) { // We've found a match! Likely a 404 page! } } else { // Page failed to load } });
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 回复

你的答案