用于捕获错误的Javascript浏览器控制台命令

问题描述 投票:0回答:1

我先打开网页,然后打开其控制台,然后键入window.location.href,然后提供网页的网址。同样,是否有任何命令可以在浏览器控制台中键入以捕获控制台错误,例如Uncaught DOMException:无法设置'domain'属性

enter image description here

javascript browser console.log
1个回答
0
投票

您可以捕获订阅了window.onerror之类的window.onerror = function(message, source, lineno, colno, error) { ... }事件的所有浏览器错误。如果仅需要检查特定元素错误,则也可以使用element.onerror。也可以订阅error事件,例如window.addEventListener('error', function(event) { ... })

例如此代码:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    window.onerror = function(message, source, lineno, colno, error) {
      console.log(message, "handled");
      return true;
    };

    throw "error";
  </script>
</body>

</html>

将捕获throw "error";引发的异常。还请注意,处理程序将在您注册后捕获错误。

© www.soinside.com 2019 - 2024. All rights reserved.