-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathshopifyBindings.ts
More file actions
67 lines (58 loc) · 2.13 KB
/
Copy pathshopifyBindings.ts
File metadata and controls
67 lines (58 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { RumPublicApi } from '@datadog/browser-rum-core'
import type { ShopifyAnalyticsApi, ShopifyPixelEvent } from './shopifyAnalytics'
export interface ElementData {
id?: string
}
export interface ErrorData {
message?: string
trace?: string
extensionName?: string
extensionTarget?: string
type?: string
appId?: string
appName?: string
appVersion?: string
}
// Matches /checkouts/*, /checkout, including locale-prefixed paths.
// Storefront pages never match, so init() is a no-op there: those pages
// already get a `DD_RUM` instance from the Theme Liquid snippet, and initializing here too would
// create a second, independent SDK instance double-tracking the same page view.
const CHECKOUT_PATH = /\/(([a-z]{2}(-[a-z0-9]+)?)\/)?(checkouts?)(\/|$)/i
/**
* Wires Shopify Web Pixel standard events to the RUM public API. `analytics` is the sandbox's
* `analytics` global (or `undefined` outside the sandbox, in which case bindings are skipped).
*/
export function initShopifyBindings(rumPublicApi: RumPublicApi, analytics: ShopifyAnalyticsApi | undefined) {
if (!analytics) {
return
}
analytics.subscribe('page_viewed', (event) => {
const url = event.context?.document?.location?.href
if (!url || !CHECKOUT_PATH.test(url)) {
return
}
rumPublicApi.startView({
url,
})
})
analytics.subscribe('clicked', (event: ShopifyPixelEvent<{ element?: ElementData }>) => {
const element = event.data?.element
const name = element?.id ?? 'element-without-id'
rumPublicApi.startAction(name, { type: 'click' })
rumPublicApi.stopAction(name, { type: 'click' })
})
// Fires when a Shopify checkout UI extension crashes.
analytics.subscribe('ui_extension_errored', (event: ShopifyPixelEvent<{ error?: ErrorData }>) => {
const error = event.data?.error
const err = new Error(error?.message)
err.stack = error?.trace
rumPublicApi.addError(err, {
extensionName: error?.extensionName,
extensionTarget: error?.extensionTarget,
extensionErrorType: error?.type,
appId: error?.appId,
appName: error?.appName,
appVersion: error?.appVersion,
})
})
}