在 <webview> 中捕获由 HTML 标签引起的 "Failed to load resources" 错误

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

我正在 Chrome 应用程序 webviews 中加载网页。

我有时会在控制台中收到一些 <script><img> 标签的消息 "Failed to load resource"。我想捕获这些错误,以便我可以在 JavaScript 代码中对它们采取行动,而不是让消息出现在控制台中。

我无法修改我正在加载的 HTML,即使用 AJAX 加载资源而不是 HTML 标签不是一个选项。 "Fixing" 资源也 不是 我正在寻找的 - 我只是想要一些 JavaScript 代码在某处知道缺少什么并从那里获取它。

我可以在代码中捕获这些错误,而不是让消息出现在控制台中吗?

试试这个:

<!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>

我只试过 img 标签就成功了。

您可以安装 <webview> WebRequest API 观察器并查看每个资源加载的状态。 这不会捕捉到您看到的资源加载失败吗?

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>']});

WebRequest API 类似于 Chrome WebRequest API