Performance: toJSON() 方法

Baseline 已广泛支持

此特性已得到良好支持,可在多种设备和浏览器版本上使用。自 2021 年 4 月起,所有浏览器均已支持此特性。

注意:此功能在 Web Workers 中可用。

toJSON() 方法是 Performance 接口的一个 序列化器;它返回 Performance 对象的 JSON 表示形式。

语法

js
toJSON()

参数

无。

返回值

一个 Performance 对象的 JSON 序列化表示。

返回的 JSON 不包含 eventCounts 属性,因为它属于 EventCounts 类型,而该类型不提供 toJSON() 方法。

注意: JSON 对象包含已弃用的 performance.timingperformance.navigation 属性的序列化。要获取较新的 PerformanceNavigationTiming 接口的 JSON 表示形式,请改用调用 PerformanceNavigationTiming.toJSON()

示例

使用 toJSON 方法

在此示例中,调用 performance.toJSON() 会返回 Performance 对象的 JSON 表示形式。

js
performance.toJSON();

这将记录一个类似如下的 JSON 对象

json
{
  "timeOrigin": 1668077531367.4,
  "timing": {
    "connectStart": 1668077531372,
    "navigationStart": 1668077531367,
    "secureConnectionStart": 0,
    "fetchStart": 1668077531372,
    "domContentLoadedEventStart": 1668077531580,
    "responseStart": 1668077531372,
    "domInteractive": 1668077531524,
    "domainLookupEnd": 1668077531372,
    "responseEnd": 1668077531500,
    "redirectStart": 0,
    "requestStart": 1668077531372,
    "unloadEventEnd": 0,
    "unloadEventStart": 0,
    "domLoading": 1668077531512,
    "domComplete": 1668077531585,
    "domainLookupStart": 1668077531372,
    "loadEventStart": 1668077531585,
    "domContentLoadedEventEnd": 1668077531580,
    "loadEventEnd": 1668077531585,
    "redirectEnd": 0,
    "connectEnd": 1668077531372
  },
  "navigation": {
    "type": 0,
    "redirectCount": 0
  }
}

要获取 JSON 字符串,可以直接使用 JSON.stringify(performance);它会自动调用 toJSON()

规范

规范
高精度时间
# dom-performance-tojson

浏览器兼容性

另见