/
adRendering.js
225 lines (209 loc) · 7.12 KB
/
adRendering.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
import {createIframe, deepAccess, inIframe, insertElement, logError, logWarn, replaceMacros} from './utils.js';
import * as events from './events.js';
import { AD_RENDER_FAILED_REASON, BID_STATUS, EVENTS, MESSAGES } from './constants.js';
import {config} from './config.js';
import {executeRenderer, isRendererRequired} from './Renderer.js';
import {VIDEO} from './mediaTypes.js';
import {auctionManager} from './auctionManager.js';
import {getCreativeRenderer} from './creativeRenderers.js';
import {hook} from './hook.js';
import {fireNativeTrackers} from './native.js';
const { AD_RENDER_FAILED, AD_RENDER_SUCCEEDED, STALE_RENDER, BID_WON } = EVENTS;
const { EXCEPTION } = AD_RENDER_FAILED_REASON;
/**
* Emit the AD_RENDER_FAILED event.
*
* @param {Object} data
* @param data.reason one of the values in AD_RENDER_FAILED_REASON
* @param data.message failure description
* @param [data.bid] bid response object that failed to render
* @param [data.id] adId that failed to render
*/
export function emitAdRenderFail({ reason, message, bid, id }) {
const data = { reason, message };
if (bid) {
data.bid = bid;
data.adId = bid.adId;
}
if (id) data.adId = id;
logError(`Error rendering ad (id: ${id}): ${message}`);
events.emit(AD_RENDER_FAILED, data);
}
/**
* Emit the AD_RENDER_SUCCEEDED event.
* (Note: Invocation of this function indicates that the render function did not generate an error, it does not guarantee that tracking for this event has occurred yet.)
* @param {Object} data
* @param data.doc document object that was used to `.write` the ad. Should be `null` if unavailable (e.g. for documents in
* a cross-origin frame).
* @param [data.bid] bid response object for the ad that was rendered
* @param [data.id] adId that was rendered.
*/
export function emitAdRenderSucceeded({ doc, bid, id }) {
const data = { doc };
if (bid) data.bid = bid;
if (id) data.adId = id;
events.emit(AD_RENDER_SUCCEEDED, data);
}
export function handleCreativeEvent(data, bidResponse) {
switch (data.event) {
case EVENTS.AD_RENDER_FAILED:
emitAdRenderFail({
bid: bidResponse,
id: bidResponse.adId,
reason: data.info.reason,
message: data.info.message
});
break;
case EVENTS.AD_RENDER_SUCCEEDED:
emitAdRenderSucceeded({
doc: null,
bid: bidResponse,
id: bidResponse.adId
});
break;
default:
logError(`Received event request for unsupported event: '${data.event}' (adId: '${bidResponse.adId}')`);
}
}
export function handleNativeMessage(data, bidResponse, {resizeFn, fireTrackers = fireNativeTrackers}) {
switch (data.action) {
case 'resizeNativeHeight':
resizeFn(data.width, data.height);
break;
default:
fireTrackers(data, bidResponse);
}
}
const HANDLERS = {
[MESSAGES.EVENT]: handleCreativeEvent
}
if (FEATURES.NATIVE) {
HANDLERS[MESSAGES.NATIVE] = handleNativeMessage;
}
function creativeMessageHandler(deps) {
return function (type, data, bidResponse) {
if (HANDLERS.hasOwnProperty(type)) {
HANDLERS[type](data, bidResponse, deps);
}
}
}
export const getRenderingData = hook('sync', function (bidResponse, options) {
const {ad, adUrl, cpm, originalCpm, width, height} = bidResponse
const repl = {
AUCTION_PRICE: originalCpm || cpm,
CLICKTHROUGH: options?.clickUrl || ''
}
return {
ad: replaceMacros(ad, repl),
adUrl: replaceMacros(adUrl, repl),
width,
height
};
})
export const doRender = hook('sync', function({renderFn, resizeFn, bidResponse, options}) {
if (FEATURES.VIDEO && bidResponse.mediaType === VIDEO) {
emitAdRenderFail({
reason: AD_RENDER_FAILED_REASON.PREVENT_WRITING_ON_MAIN_DOCUMENT,
message: 'Cannot render video ad',
bid: bidResponse,
id: bidResponse.adId
});
return;
}
const data = getRenderingData(bidResponse, options);
renderFn(Object.assign({adId: bidResponse.adId}, data));
const {width, height} = data;
if ((width ?? height) != null) {
resizeFn(width, height);
}
});
doRender.before(function (next, args) {
// run renderers from a high priority hook to allow the video module to insert itself between this and "normal" rendering.
const {bidResponse, doc} = args;
if (isRendererRequired(bidResponse.renderer)) {
executeRenderer(bidResponse.renderer, bidResponse, doc);
emitAdRenderSucceeded({doc, bid: bidResponse, id: bidResponse.adId})
next.bail();
} else {
next(args);
}
}, 100)
export function handleRender({renderFn, resizeFn, adId, options, bidResponse, doc}) {
if (bidResponse == null) {
emitAdRenderFail({
reason: AD_RENDER_FAILED_REASON.CANNOT_FIND_AD,
message: `Cannot find ad '${adId}'`,
id: adId
});
return;
}
if (bidResponse.status === BID_STATUS.RENDERED) {
logWarn(`Ad id ${adId} has been rendered before`);
events.emit(STALE_RENDER, bidResponse);
if (deepAccess(config.getConfig('auctionOptions'), 'suppressStaleRender')) {
return;
}
}
try {
doRender({renderFn, resizeFn, bidResponse, options, doc});
} catch (e) {
emitAdRenderFail({
reason: AD_RENDER_FAILED_REASON.EXCEPTION,
message: e.message,
id: adId,
bid: bidResponse
});
}
auctionManager.addWinningBid(bidResponse);
events.emit(BID_WON, bidResponse);
}
export function renderAdDirect(doc, adId, options) {
let bid;
function fail(reason, message) {
emitAdRenderFail(Object.assign({id: adId, bid}, {reason, message}));
}
function resizeFn(width, height) {
if (doc.defaultView && doc.defaultView.frameElement) {
width && (doc.defaultView.frameElement.width = width);
height && (doc.defaultView.frameElement.height = height);
}
}
const messageHandler = creativeMessageHandler({resizeFn});
function renderFn(adData) {
if (adData.ad) {
doc.write(adData.ad);
doc.close();
emitAdRenderSucceeded({doc, bid, adId: bid.adId});
} else {
getCreativeRenderer(bid)
.then(render => render(adData, {
sendMessage: (type, data) => messageHandler(type, data, bid),
mkFrame: createIframe,
}, doc.defaultView))
.then(
() => emitAdRenderSucceeded({doc, bid, adId: bid.adId}),
(e) => {
fail(e?.reason || AD_RENDER_FAILED_REASON.EXCEPTION, e?.message)
e?.stack && logError(e);
}
);
}
// TODO: this is almost certainly the wrong way to do this
const creativeComment = document.createComment(`Creative ${bid.creativeId} served by ${bid.bidder} Prebid.js Header Bidding`);
insertElement(creativeComment, doc, 'html');
}
try {
if (!adId || !doc) {
fail(AD_RENDER_FAILED_REASON.MISSING_DOC_OR_ADID, `missing ${adId ? 'doc' : 'adId'}`);
} else {
bid = auctionManager.findBidByAdId(adId);
if ((doc === document && !inIframe())) {
fail(AD_RENDER_FAILED_REASON.PREVENT_WRITING_ON_MAIN_DOCUMENT, `renderAd was prevented from writing to the main document.`);
} else {
handleRender({renderFn, resizeFn, adId, options: {clickUrl: options?.clickThrough}, bidResponse: bid, doc});
}
}
} catch (e) {
fail(EXCEPTION, e.message);
}
}