一些 Chrome 浏览器的前端调试技巧

分享背景

工欲善其事必先利其器javascript

断点

  • 条件断点
  • 异常断点

格式化压缩代码

Chrome inspector -> Sources tab -> {}
复制代码

选择DOM元素

控制台支持一些变量和函数来选择DOM元素:java

$() 至关于document.querySelector()
// 返回第一个与之匹配的CSS选择器的元素
// 例如:$('div')它将返回本页的第一个div元素

 $$() 至关于document.querySelectorAll()
// 返回一个数组,里面是与之匹配的CSS选择器的元素

 $0~$4 依次返回五个最近你在元素面板选择过的DOM元素的历史记录
 $0是最新的记录,以此类推

 $_  获取上次表达式结果
复制代码

API工具方法

keys()

  • 至关于Object.keys()

values()

  • 至关于Object.values()

monitor/unmonitor

  • 用来观察函数调用的工具方法。在函数调用的时候,能够同步输出函数名以及参数。
function add(a,b){return a+b}
monitor(add)
add(1,2)
// output:
// function add called with arguments: 1, 2
// 3
复制代码

monitorEvents/unmonitorEvents

  • 观察对象事件
// 单个事件
monitorEvents(window, "resize")
resize Event {isTrusted: true, type: "resize", target: Window, currentTarget: Window, eventPhase: 2, …}

// 多个事件
monitorEvents($0, ['mousedown', 'mouseup'])
mousedown MouseEvent {isTrusted: true, screenX: -1034, screenY: 94, clientX: 28, clientY: 674, …}

// 全部事件
monitorEvents($0)

// 取消事件
unmonitorEvents($0)
复制代码

getEventListeners

  • 获取注册到一个对象上的全部事件监听器~

console

keys(console)   //查看全部的console方法

 ["debug", "error", "info", "log", "warn", "dir", "dirxml", "table",
 "trace", "group", "groupCollapsed", "groupEnd", "clear", "count",
 "countReset", "assert", "profile", "profileEnd", "time", "timeLog",
 "timeEnd", "timeStamp", "context", "memory"]
复制代码

代码执行时间

let startTime = new Date().getTime();

console.log("started");

setTimeout(() => {
  console.log(
    "ended in " + (new Date().getTime() - startTime) + " milliseconds"
  );
}, 3000);
// output:
// "started"
// "ended in 3001 milliseconds"
复制代码
console.time('Call to doSomething took')
doSomething()
console.timeEnd('Call to doSomething took')

// output: 
// Call to doSomething took:300ms
复制代码
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

// output: 
// Call to doSomething took 300 milliseconds
复制代码

日志显示时间戳

设置 -> Show timestampsweb

保留历史记录

console -> 设置 -> 勾选 preserve logchrome

编辑页面

document.designMode = "on"
复制代码

清除控制台

  • 在控制台中点击右键,而后按 Clear console。
  • 在控制台中输入 clear()。
  • 从您的 JavaScript 代码内调用 console.clear()。
  • 按 Ctrl+L(Mac、Windows、Linux)

参考资料

相关文章
相关标签/搜索