chrome断点使用归纳

263 阅读3分钟

参考地址: developer.chrome.com/docs/devtoo…

断点类型何时使用
Line-of-code在合适的地方打上断点
Conditional line-of-code在满足条件的情况下打上断点
Logpoint不打断点,只输出信息,类似console
DOM在更改或删除特定DOM节点或其子节点的代码上暂停。
XHR当XHR URL包含字符串时打断点
Event listener在触发事件时打上断点, 例如 click
Exception在触发已抓取(caught)或未抓取(uncaught)的错误时打上断点
Function在特定的函数触发时打上断点

Line-of-code

使用line-of-code断点在你需要查看的代码片段上. 开发工具会在执行该代码前进行终止

译者:这个就是我们普通的调式断点

image.png

如上图,会在在断点处循环打点100次。

也可以使用代码内嵌的形式进行断点调试

console.log('a');
console.log('b');
debugger;
console.log('c');

### Conditional line-of-code breakpoints (条件断点)

如何设置条件断点?

  • 右键断点处,点击edit

image.png

  • 选中conditional breakpoint

image.png

可以在满足条件的情况下才进入断点,例如这样设置:

image.png

只有在i=6时才会进入断点。

Log line-of-code breakpoints (日志断点)

日志断点不会进入断点,只会像console一样输出内容

如何进入日志断点

  • 右键断点处,点击edit

image.png

  • 选中 log breakpoint

image.png

可以在控制台中查看输出:

image.png

Edit line-of-code breakpoints(断点操作面板)

可以在浏览器的右侧查看该页面的断点操作面板

image.png

可以快速点位断点的位置,并进行统一的管理操作

image.png

DOM change breakpoints

在页面上dom元素发生变化时,在触发变化的语句上打上断点

如何设置DOM 变化断点

  • 右键要监听的dom
  • 选择break on
  • 选择要监听的dom变化情况(子节点变化节点属性变化节点删除)

image.png

DOM的变化类型

  • Subtree modifications. Triggered when a child of the currently-selected node is removed or added, or the contents of a child are changed. Not triggered on child node attribute changes, or on any changes to the currently-selected node.
  • Attributes modifications: Triggered when an attribute is added or removed on the currently-selected node, or when an attribute value changes.
  • Node Removal: Triggered when the currently-selected node is removed.

实例:

<html>
    <head></head>
    <body>
        <div id="count"></div>
        <button onclick="addCount()">+1</button>
        <script>
            function addCount() {
                countDom.innerHTML = ++count;
            }
            const countDom = document.getElementById("count");
            let count = 0;
        </script>
    </body>
</html>

点击+1按钮后,触发断点,定位到触发DOM变化的节点

image.png

XHR/fetch breakpoints

XHR或者fetch访问特定的地址时,进入该断点

如何触发XHR/fetch breakpoints

  • 在source中选中相应的页面
  • 进入断点控制面板XHR/fetch breakpoints,增加断点

image.png

可以填写访问地址需要包含的内容

image.png 例如上图,就只会在test1处打上断点。

Event listener breakpoints

触发对应事件时,进入该断点

如何触发event listener breakpoints

  • 在source面板中选中相应的页面
  • 进入断点控制面板event listener breakpoint,增加断点

image.png

例如上图,可以在点击按钮时,可以在触发mouse事件的代码处打上断点

Function breakpoints

使用debug包裹函数,在被包裹函数触发时,在触发函数的代码处打上断点

function sum(a, b) {
  let result = a + b; // DevTools pauses on this line.
  return result;
}
debug(sum); // Pass the function object, not a string.
sum();

此时会在sum执行时,进入断点(只能在控制台调用,代码中无法写入

Exception breakpoints

image.png

断点控制面板中可以找到(老版本的chrome在console的右上角),在caught或者uncaught的代码处打上断点(在排查问题时非常实用