-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathzoid-polyfill.js
More file actions
253 lines (226 loc) · 9.44 KB
/
zoid-polyfill.js
File metadata and controls
253 lines (226 loc) · 9.44 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/* global Android */
import { isAndroidWebview, isIosWebview, getPerformance } from '@krakenjs/belter/src';
import { getOrCreateDeviceID, logger } from '../../../../utils';
import { isIframe, validateProps, sendEventAck } from './utils';
const IOS_INTERFACE_NAME = 'paypalMessageModalCallbackHandler';
const ANDROID_INTERFACE_NAME = 'paypalMessageModalCallbackHandler';
function listenAndAssignProps(newProps, propListeners) {
Array.from(propListeners.values()).forEach(listener => {
listener({ ...window.xprops, ...newProps });
});
Object.assign(window.xprops, newProps);
}
export function validateAndUpdateBrowserProps(initialProps, propListeners, updatedPropsEvent) {
const {
origin: eventOrigin,
data: { eventName, id, eventPayload: newProps }
} = updatedPropsEvent;
const merchantOrigin = decodeURIComponent(initialProps.origin);
if (eventOrigin === merchantOrigin && eventName === 'PROPS_UPDATE' && newProps && typeof newProps === 'object') {
// send event ack so PostMessenger will stop reposting event
sendEventAck(id, merchantOrigin);
const validProps = validateProps(newProps);
listenAndAssignProps(validProps, propListeners);
}
}
const setupBrowser = props => {
const propListeners = new Set();
window.addEventListener(
'message',
event => {
validateAndUpdateBrowserProps(props, propListeners, event);
},
false
);
window.xprops = {
onProps: listener => propListeners.add(listener),
// TODO: Verify these callbacks are instrumented correctly
onReady: ({ products, meta }) => {
const { clientId, payerId, merchantId, offer, partnerAttributionId } = props;
const { trackingDetails } = meta;
logger.addMetaBuilder(existingMeta => {
// Remove potential existing meta info
// Necessary because beaver-logger will not override an existing meta key if these values change
// eslint-disable-next-line no-param-reassign
delete existingMeta[1];
// Need to capture existing attributes under global before destroying
const { global: existingGlobal = {} } = existingMeta;
// eslint-disable-next-line no-param-reassign
delete existingMeta.global;
return {
global: {
...existingGlobal,
// integration_type needs to be sent or it will default to lander
integration_type: props.integrationType ?? __MESSAGES__.__TARGET__,
// Device ID should be correctly set during message render
deviceID: getOrCreateDeviceID()
// sessionID: getSessionID()
},
1: {
// TODO: This should likely be specific to this integration type
type: 'modal',
// messageRequestId,
account: merchantId || clientId || payerId,
trackingDetails
}
};
});
logger.track({
index: '1',
et: 'CLIENT_IMPRESSION',
event_type: 'modal_rendered',
modal: `${products.join('_').toLowerCase()}:${offer ? offer.toLowerCase() : products[0]}`,
// For standalone modal the stats event does not run, so we duplicate some data here
bn_code: partnerAttributionId
// first_modal_render_delay: Math.round(firstModalRenderDelay).toString(),
// render_duration: Math.round(getCurrentTime() - renderStart).toString()
});
},
onClick: ({ linkName, src }) => {
logger.track({
index: '1',
et: 'CLICK',
event_type: 'modal_rendered',
page_view_link_name: linkName,
page_view_link_source: src ?? linkName
});
},
onCalculate: ({ value }) => {
logger.track({
index: '1',
et: 'CLICK',
event_type: 'modal_rendered',
page_view_link_name: 'Calculator',
page_view_link_source: 'Calculator',
calculator_input: value
});
},
onShow: () => {
logger.track({
index: '1',
et: 'CLIENT_IMPRESSION',
event_type: 'modal_viewed',
page_view_link_source: 'Show'
});
},
onClose: ({ linkName }) => {
if (isIframe && document.referrer) {
const targetOrigin = new window.URL(document.referrer).origin;
window.parent.postMessage('paypal-messages-modal-close', targetOrigin);
}
logger.track({
index: '1',
et: 'CLICK',
event_type: 'modal_close',
page_view_link_name: linkName
});
},
// Overridable defaults
integrationType: __MESSAGES__.__TARGET__,
// Specified props via query params
...props
};
};
const setupWebview = props => {
const postMessage = (() => {
if (window.webkit?.messageHandlers?.[IOS_INTERFACE_NAME]) {
return window.webkit.messageHandlers[IOS_INTERFACE_NAME].postMessage.bind(
window.webkit.messageHandlers[IOS_INTERFACE_NAME]
);
}
// `Android` is not on the `window` object but rather an adjacent top level object
if (typeof Android !== 'undefined') {
return Android[ANDROID_INTERFACE_NAME].bind(Android);
}
// This scenario should only ever occur when developing locally
// eslint-disable-next-line no-console
return payload => console.warn('postMessage:', JSON.parse(payload));
})();
const propListeners = new Set();
const sendCallbackMessage = (name, ...args) => postMessage(JSON.stringify({ name, args }));
// Functions called from the native app
window.actions = {
updateProps: newProps => {
if (newProps && typeof newProps === 'object') {
listenAndAssignProps(newProps, propListeners);
}
}
};
window.xprops = {
onProps: listener => propListeners.add(listener),
onReady: ({ meta }) => {
const { trackingDetails } = meta;
const performance = getPerformance();
const timing = performance?.getEntriesByType('navigation')[0];
sendCallbackMessage('onReady', {
__shared__: {
// Analytic Details
fdata: trackingDetails.fdata,
experimentation_experience: trackingDetails.experimentation_experience_ids,
experimentation_treatment: trackingDetails.experimentation_treatment_ids,
credit_product_identifiers: trackingDetails.credit_product_identifiers,
offer_country_code: trackingDetails.offer_country_code,
merchant_country_code: trackingDetails.merchant_country_code,
views: trackingDetails.views,
qualified_products: trackingDetails.qualified_products,
debug_id: trackingDetails.debug_id
},
event_type: 'modal_rendered',
request_duration: timing && Math.round(timing.responseEnd - timing.requestStart).toString(),
render_duration: timing && Math.round(performance.now() - timing.responseEnd).toString()
});
},
onClick: ({ linkName, src = linkName }) => {
sendCallbackMessage('onClick', {
event_type: 'modal_clicked',
page_view_link_name: linkName,
page_view_link_source: src
});
},
onCalculate: ({ value }) => {
sendCallbackMessage('onCalculate', {
event_type: 'modal_clicked',
page_view_link_name: 'Calculator',
page_view_link_source: 'Calculator',
calculator_input: value
});
},
onShow: () => {
sendCallbackMessage('onShow', {
event_type: 'modal_viewed',
page_view_link_name: 'Show',
page_view_link_source: 'Show'
});
},
onClose: ({ linkName, src = linkName }) => {
sendCallbackMessage('onClose', {
event_type: 'modal_closed',
page_view_link_name: linkName,
page_view_link_source: src
});
},
// Overridable defaults
integrationType: __MESSAGES__.__TARGET__,
// Specified props via query params
...props
};
};
export default function polyfillZoid() {
const props = window.location.search
.slice(1)
.split('&')
.reduce((acc, query) => {
const [key, value] = query.split('=');
if (value) {
const propName = key.replace(/_([a-z])/g, (_, p1) => p1.toUpperCase());
acc[propName] = value;
}
return acc;
}, {});
const { userAgent } = window.navigator;
if (isIosWebview(userAgent) || isAndroidWebview(userAgent)) {
setupWebview(props);
} else {
setupBrowser(props);
}
}