forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreconciliationRtdProvider.js
299 lines (262 loc) · 6.86 KB
/
reconciliationRtdProvider.js
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
* This module adds reconciliation provider to the real time data module
* The {@link module:modules/realTimeData} module is required
* The module will add custom targetings to ad units
* The module will listen to post messages from rendered creatives with Reconciliation Tag
* The module will call tracking pixels to log info needed for reconciliation matching
* @module modules/reconciliationRtdProvider
* @requires module:modules/realTimeData
*/
/**
* @typedef {Object} ModuleParams
* @property {string} publisherMemberId
* @property {?string} initUrl
* @property {?string} impressionUrl
* @property {?boolean} allowAccess
*/
import {submodule} from '../src/hook.js';
import {ajaxBuilder} from '../src/ajax.js';
import {generateUUID, isGptPubadsDefined, logError, timestamp} from '../src/utils.js';
import {find} from '../src/polyfill.js';
/**
* @typedef {import('../modules/rtdModule/index.js').RtdSubmodule} RtdSubmodule
*/
/** @type {Object} */
const MessageType = {
IMPRESSION_REQUEST: 'rsdk:impression:req',
IMPRESSION_RESPONSE: 'rsdk:impression:res',
};
/** @type {ModuleParams} */
const DEFAULT_PARAMS = {
initUrl: 'https://confirm.fiduciadlt.com/init',
impressionUrl: 'https://confirm.fiduciadlt.com/pimp',
allowAccess: false,
};
/** @type {ModuleParams} */
let _moduleParams = {};
/**
* Handle postMesssage from ad creative, track impression
* and send response to reconciliation ad tag
* @param {Event} e
*/
function handleAdMessage(e) {
let data = {};
let adUnitId = '';
let adDeliveryId = '';
try {
data = JSON.parse(e.data);
} catch (e) {
return;
}
if (data.type === MessageType.IMPRESSION_REQUEST) {
if (isGptPubadsDefined()) {
// 1. Find the last iframed window before window.top where the tracker was injected
// (the tracker could be injected in nested iframes)
const adWin = getTopIFrameWin(e.source);
if (adWin && adWin !== window.top) {
// 2. Find the GPT slot for the iframed window
const adSlot = getSlotByWin(adWin);
// 3. Get AdUnit IDs for the selected slot
if (adSlot) {
adUnitId = adSlot.getAdUnitPath();
adDeliveryId = adSlot.getTargeting('RSDK_ADID');
adDeliveryId = adDeliveryId.length
? adDeliveryId[0]
: `${timestamp()}-${generateUUID()}`;
}
}
}
// Call local impression callback
const args = Object.assign({}, data.args, {
publisherDomain: window.location.hostname,
publisherMemberId: _moduleParams.publisherMemberId,
adUnitId,
adDeliveryId,
});
track.trackPost(_moduleParams.impressionUrl, args);
// Send response back to the Advertiser tag
let response = {
type: MessageType.IMPRESSION_RESPONSE,
id: data.id,
args: Object.assign(
{
publisherDomain: window.location.hostname,
},
data.args
),
};
// If access is allowed - add ad unit id to response
if (_moduleParams.allowAccess) {
Object.assign(response.args, {
adUnitId,
adDeliveryId,
});
}
e.source.postMessage(JSON.stringify(response), '*');
}
}
/**
* Get top iframe window for nested Window object
* - top
* -- iframe.window <-- top iframe window
* --- iframe.window
* ---- iframe.window <-- win
*
* @param {Window} win nested iframe window object
* @param {Window} topWin top window
*/
export function getTopIFrameWin(win, topWin) {
topWin = topWin || window;
if (!win) {
return null;
}
try {
while (win.parent !== topWin) {
win = win.parent;
}
return win;
} catch (e) {
return null;
}
}
/**
* get all slots on page
* @return {Object[]} slot GoogleTag slots
*/
function getAllSlots() {
return isGptPubadsDefined() && window.googletag.pubads().getSlots();
}
/**
* get GPT slot by placement id
* @param {string} code placement id
* @return {?Object}
*/
function getSlotByCode(code) {
const slots = getAllSlots();
if (!slots || !slots.length) {
return null;
}
return (
find(
slots,
(s) => s.getSlotElementId() === code || s.getAdUnitPath() === code
) || null
);
}
/**
* get GPT slot by iframe window
* @param {Window} win
* @return {?Object}
*/
export function getSlotByWin(win) {
const slots = getAllSlots();
if (!slots || !slots.length) {
return null;
}
return (
find(slots, (s) => {
let slotElement = document.getElementById(s.getSlotElementId());
if (slotElement) {
let slotIframe = slotElement.querySelector('iframe');
if (slotIframe && slotIframe.contentWindow === win) {
return true;
}
}
return false;
}) || null
);
}
/**
* Init Reconciliation post messages listeners to handle
* impressions messages from ad creative
*/
function initListeners() {
window.addEventListener('message', handleAdMessage, false);
}
/**
* Send init event to log
* @param {Array} adUnits
*/
function trackInit(adUnits) {
track.trackPost(
_moduleParams.initUrl,
{
adUnits,
publisherDomain: window.location.hostname,
publisherMemberId: _moduleParams.publisherMemberId,
}
);
}
/**
* Track event via POST request
* wrap method to allow stubbing in tests
* @param {string} url
* @param {Object} data
*/
export const track = {
trackPost(url, data) {
const ajax = ajaxBuilder();
ajax(
url,
function() {},
JSON.stringify(data),
{
method: 'POST',
}
);
}
}
/**
* Set custom targetings for provided adUnits
* @param {string[]} adUnitsCodes
* @return {Object} key-value object with custom targetings
*/
function getReconciliationData(adUnitsCodes) {
const dataToReturn = {};
const adUnitsToTrack = [];
adUnitsCodes.forEach((adUnitCode) => {
if (!adUnitCode) {
return;
}
const adSlot = getSlotByCode(adUnitCode);
const adUnitId = adSlot ? adSlot.getAdUnitPath() : adUnitCode;
const adDeliveryId = `${timestamp()}-${generateUUID()}`;
dataToReturn[adUnitCode] = {
RSDK_AUID: adUnitId,
RSDK_ADID: adDeliveryId,
};
adUnitsToTrack.push({
adUnitId,
adDeliveryId
});
}, {});
// Track init event
trackInit(adUnitsToTrack);
return dataToReturn;
}
/** @type {RtdSubmodule} */
export const reconciliationSubmodule = {
/**
* used to link submodule with realTimeData
* @type {string}
*/
name: 'reconciliation',
/**
* get data and send back to realTimeData module
* @function
* @param {string[]} adUnitsCodes
*/
getTargetingData: getReconciliationData,
init: init,
};
function init(moduleConfig) {
const params = moduleConfig.params;
if (params && params.publisherMemberId) {
_moduleParams = Object.assign({}, DEFAULT_PARAMS, params);
initListeners();
} else {
logError('missing params for Reconciliation provider');
}
return true;
}
submodule('realTimeData', reconciliationSubmodule);