Catching “Failed to load resources” errors caused by HTML tags in a <webview>

扶醉桌前 提交于 2019-12-08 06:13:05

问题


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, i.e., 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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/28164462/catching-failed-to-load-resources-errors-caused-by-html-tags-in-a-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!