Web应用调试利器:queryObjects

4,465 阅读2分钟

queryObjects是Chrome 62新增的一个Command Line API

官网这样介绍该API

A new API for querying heap objects

Call queryObjects(Constructor) from the Console to return an array of objects that were created with the specified constructor. For example:

  • queryObjects(Promise). Returns all Promises.
  • queryObjects(HTMLElement). Returns all HTML elements.
  • queryObjects(foo), where foo is a function name. Returns all objects that were instantiated via new foo().
  • The scope of queryObjects() is the currently-selected execution context in the Console. See Selecting execution context.

API具体介绍

queryObjects(Constructor) 可以去查找currently-selected execution context中指定Constructor的所有实例

execution context

  • execution context是代码的执行环境,默认为top。其他的execution context可以来自内嵌的iframe、ExtensionsService Worker

Constructor

  • 其实queryObjects接受的第一个参数的值类型可以是函数也可以是对象,当是函数时,是使用函数的prototype属性值作为查找的原型对象
  • 所以在控制台中使用queryObjects(RegExp)queryObjects(RegExp.prototype)最终得到的结果是相同的。

实例

  • 准确来说 queryObjects从当前execution context中的所有对象中过滤出原型链中包含指定原型对象的对象。 所以有以下情况。

queryObjects(Object)的结果会包含queryObjects(Array)的结果

使用案例

对生产环境的项目进行调试,获取特定的实例对象

  • 希望获取.shoplist对应的Vue组件实例。
  • 先通过queryObjects(Object)获取所有的对象,Vue组件实例必定包含在其中,将异步结果值存为全局变量temp1
  • 再通过temp1.filter(a=>a.shopList)过滤出结果。

获取其他常用对象

  • 获取所有的RegExpDate对象,
queryObjects(RegExp);
queryObjects(Date);
  • 获取所有Generator 函数async 函数
queryObjects(Function) // 将异步结果值存为全局变量temp1

----------
temp1.filter(item => {
  return foo[Symbol.toStringTag] === 'GeneratorFunction'
});
temp1.filter(item => {
  return foo[Symbol.toStringTag] === 'AsyncFunction'
});
  • 获取经过webpack打包的esModule
queryObjects(Object) // 将异步结果值存为全局变量temp1

----------
temp1.filter(a=>a.__esModule)