如何使用JavaScript检测页面404错误? [英] How to detect on-page 404 errors using JavaScript?

查看:1578
本文介绍了如何使用JavaScript检测页面404错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML页面,其中引用了几个JavaScript,CSS和图像文件。这些引用是动态注入的,用户可以手动将HTML页面和支持文件复制到另一台机器。

I have an HTML page where several JavaScript, CSS and images files are referenced. These references are dynamically injected and user can manually copy the HTML page and the support files to another machine.

如果某些JS或CSS丢失,浏览器会在控制台中发出抱怨。例如:

If some JS or CSS are missing, the browser complains in the console. For example:


错误GET文件:/// E:/SSC_Temp/html_005/temp/Support/jquery.js

Error GET file:///E:/SSC_Temp/html_005/temp/Support/jquery.js

我需要以某种方式将这些错误报告给我的HTML页面的内联JavaScript,以便我可以要求用户首先验证是否正确复制了支持文件。

I need somehow these errors reported back to me on the inline JavaScript of the HTML page so I can ask user to first verify that support files are copied correctly.

这里有 window.onerror 事件,它告诉我在页面上有一个JS错误,例如意外的语法错误,但在<404>未找到错误事件中不会触发。我希望在任何资源类型的情况下检查这种情况,包括CSS,JS和图像。

There's the window.onerror event which just inform me that there's a JS error on the page such as an Unexpected Syntax error, but this doesn't fire in the event of a 404 Not Found error. I want to check for this condition in case of any resource type, including CSS, JS, and images.

我不喜欢使用jQuery AJAX来物理验证文件存在 - 对于每个页面加载,I / O开销都很昂贵。

I do not like to use jQuery AJAX to verify that file physically exists - the I/O overhead is expensive for every page load.

错误报告必须包含文件的名称,以便我可以检查文件是核心文件还是可选文件。

The error report has to contain the name of the file missing so I can check if the file is core or optional.

任何想法?

推荐答案

捕获所有 / code>事件,您可以使用 addEventListener useCapture 参数设置为 true 。原因 window.onerror 不会这样做,因为它使用了气泡事件阶段,并且需要错误事件捕获不会冒泡。

To capture all error events on the page, you can use addEventListener with the useCapture argument set to true. The reason window.onerror will not do this is because it uses the bubble event phase, and the error events you want to capture do not bubble.

如果在加载任何外部内容之前将以下脚本添加到HTML中,则应该能够捕获所有错误事件,即使在离线加载时也是如此。

If you add the following script to your HTML before you load any external content, you should be able to capture all the error events, even when loading offline.

<script type="text/javascript">
window.addEventListener('error', function(e) {
    console.log(e);
}, true);
</script>

您可以通过 e.target 访问导致错误的元素。 code>。例如,如果你想知道什么文件没有加载到 img 标签上,你可以使用 e.target.src 以获取未能加载的网址。

You can access the element that caused the error through e.target. For example, if you want to know what file did not load on an img tag, you can use e.target.src to get the URL that failed to load.

这篇关于如何使用JavaScript检测页面404错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆