From a80b3ddb4a938adb4054938bb7550fecb546e2a7 Mon Sep 17 00:00:00 2001 From: Xinyi Ye Date: Tue, 17 Dec 2024 16:19:42 -0800 Subject: [PATCH] fix: should default to empty string when document.title is not string --- .../src/page-view-tracking.ts | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/plugin-page-view-tracking-browser/src/page-view-tracking.ts b/packages/plugin-page-view-tracking-browser/src/page-view-tracking.ts index a985c69a6..655f38f4f 100644 --- a/packages/plugin-page-view-tracking-browser/src/page-view-tracking.ts +++ b/packages/plugin-page-view-tracking-browser/src/page-view-tracking.ts @@ -34,6 +34,25 @@ export const pageViewTrackingPlugin: CreatePageViewTrackingPlugin = (options: Op return decodedLocationStr; }; + /* istanbul ignore next */ + const getDocumentTitle = () => { + if (typeof document === 'undefined') { + localConfig?.loggerProvider.warn('document is undefined. Default [Amplitude] Page Title to an empty string'); + return ''; + } + + const title = document.title; + if (typeof title !== 'string') { + localConfig?.loggerProvider.warn( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `document.title is not a string. Default [Amplitude] Page Title to an empty string. document.title: ${title}`, + ); + return ''; + } + + return title; + }; + const createPageViewEvent = async (): Promise => { /* istanbul ignore next */ const locationHREF = getDecodeURI((typeof location !== 'undefined' && location.href) || ''); @@ -46,7 +65,7 @@ export const pageViewTrackingPlugin: CreatePageViewTrackingPlugin = (options: Op '[Amplitude] Page Location': locationHREF, '[Amplitude] Page Path': /* istanbul ignore next */ (typeof location !== 'undefined' && getDecodeURI(location.pathname)) || '', - '[Amplitude] Page Title': /* istanbul ignore next */ (typeof document !== 'undefined' && document.title) || '', + '[Amplitude] Page Title': getDocumentTitle(), '[Amplitude] Page URL': locationHREF.split('?')[0], }, };