I am loading web pages in Chrome App webviews .
I sometimes get "Failed to load resource" messages in the console for some of the <script>
and <img>
tags. I want to catch these errors so I can act on them in JavaScript code, rather than have messages appear in the console.
I can not modify the HTML that I am loading, ie, using AJAX to load the resources rather than HTML tags is not an option. "Fixing" the resources is also not what I am looking for - I just want some JavaScript code somewhere to know what is missing and take it from there.
Can I catch these errors in code, rather than having messages appear in the console?
You can install a <webview> WebRequest API observer and see each resource load's status. Does that not catch the resource load failures you're seeing?
var webview = document.querySelector('webview'); webview.request.onHeadersReceived.addListener(function(details) { if (details.statusLine.match(/^HTTP.*404/) { // some 404 happened... window.console.log('Failed url: ' + details.url); } else if ... }, {urls: ['<all_urls>']});
The <webview> WebRequest API is similar to the Chrome WebRequest API .
Try this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>These code might catch img load errors</h1>
<img id="img-1" src="url.jpg"/>
<script type="text/javascript">
(function(){
var img = document.getElementById('img-1');
if (img.complete) {
console.log('the img is already loaded.');
}else{
img.addEventListener('load', function(){
console.log('img loaded.');
});
}
img.addEventListener('error', function(){
console.log('loading img failed.'); // you could try to load that resource again.
});
})();
</script>
</body>
</html>
I've only tried img
tag and it worked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.