How to detect on-page 404 errors using JavaScript?

前端 未结 4 1825
借酒劲吻你
借酒劲吻你 2020-12-05 00:30

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

4条回答
  •  北海茫月
    2020-12-05 00:55

    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.

    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.

    
    

    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.

    NOTE: This technically will not detect the error code, it detects if the image failed to load, as it technically behaves the same regardless of the status code. Depending on your setup this would probably be enough, but for example if a 404 is returned with a valid image it will not trigger an error event.

提交回复
热议问题