js capture resource loading errors

Resource loading error use addEventListener to monitor error event capture

Implementation principle: When a resource (such as <img> or <script>) fails to load, the element that loads the resource will trigger an error event of the Event interface and execute the onerror() processing function on the element.

These error events will not bubble up to the window, but can be captured by window.addEventListener in the capture phase.

But here you need to pay attention, because addEventListener mentioned above can also catch js errors, it needs to be filtered to avoid repeated reports, and only report when it is judged to be a resource error.

window.addEventListener('error', event => (){ 
  // 过滤js error
  let target = event.target || event.srcElement;
  let isElementTarget = target instanceof HTMLScriptElement || target instanceof HTMLLinkElement || target instanceof HTMLImageElement;
  if (!isElementTarget) return false;
  // 上报资源地址
  let url = target.src || target.href;
  console.log(url);
}, true);

Guess you like

Origin blog.csdn.net/lianjiuxiao/article/details/113506232