From 18871c6e2a1ae4a355d1b487790a5e32176f1444 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20Og=C3=B3rek?= Date: Mon, 1 Feb 2021 15:06:53 +0100 Subject: [PATCH] Don't break when function call context is undefined --- packages/utils/src/instrument.ts | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/packages/utils/src/instrument.ts b/packages/utils/src/instrument.ts index d4263e1a9ab9..b75f32fa1849 100644 --- a/packages/utils/src/instrument.ts +++ b/packages/utils/src/instrument.ts @@ -531,17 +531,22 @@ function instrumentDOM(): void { options?: boolean | AddEventListenerOptions, ): AddEventListener { if (type === 'click' || type == 'keypress') { - const el = this as InstrumentedElement; - const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); - const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 }); - - if (!handlerForType.handler) { - const handler = makeDOMEventHandler(triggerDOMHandler); - handlerForType.handler = handler; - originalAddEventListener.call(this, type, handler, options); - } + try { + const el = this as InstrumentedElement; + const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); + const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 }); - handlerForType.refCount += 1; + if (!handlerForType.handler) { + const handler = makeDOMEventHandler(triggerDOMHandler); + handlerForType.handler = handler; + originalAddEventListener.call(this, type, handler, options); + } + + handlerForType.refCount += 1; + } catch (e) { + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. + } } return originalAddEventListener.call(this, type, listener, options); @@ -576,7 +581,8 @@ function instrumentDOM(): void { } } } catch (e) { - // accessing dom properties is always fragile + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. } }