mk9-prebid
Version:
Header Bidding Management Library
72 lines (63 loc) • 2.44 kB
HTML
<script>
// this script can be returned by an ad server delivering a cross domain iframe, into which the
// creative will be rendered, e.g. DFP delivering a SafeFrame
let windowLocation = window.location;
var urlParser = document.createElement('a');
urlParser.href = '%%PATTERN:url%%';
var publisherDomain = urlParser.protocol + '//' + urlParser.hostname;
function renderAd(ev) {
var key = ev.message ? 'message' : 'data';
var adObject = {};
try {
adObject = JSON.parse(ev[key]);
} catch (e) {
return;
}
var origin = ev.origin || ev.originalEvent.origin;
if (adObject.message && adObject.message === 'Prebid Response' &&
publisherDomain === origin &&
adObject.adId === '%%PATTERN:hb_adid%%' &&
(adObject.ad || adObject.adUrl)) {
var body = window.document.body;
var ad = adObject.ad;
var url = adObject.adUrl;
var width = adObject.width;
var height = adObject.height;
if (adObject.mediaType === 'video') {
console.log('Error trying to write ad.');
} else
if (ad) {
var frame = document.createElement('iframe');
frame.setAttribute('FRAMEBORDER', 0);
frame.setAttribute('SCROLLING', 'no');
frame.setAttribute('MARGINHEIGHT', 0);
frame.setAttribute('MARGINWIDTH', 0);
frame.setAttribute('TOPMARGIN', 0);
frame.setAttribute('LEFTMARGIN', 0);
frame.setAttribute('ALLOWTRANSPARENCY', 'true');
frame.setAttribute('width', width);
frame.setAttribute('height', height);
body.appendChild(frame);
frame.contentDocument.open();
frame.contentDocument.write(ad);
frame.contentDocument.close();
} else if (url) {
body.insertAdjacentHTML('beforeend', '<IFRAME SRC="' + url + '" FRAMEBORDER="0" SCROLLING="no" MARGINHEIGHT="0" MARGINWIDTH="0" TOPMARGIN="0" LEFTMARGIN="0" ALLOWTRANSPARENCY="true" WIDTH="' + width + '" HEIGHT="' + height + '"></IFRAME>');
} else {
console.log('Error trying to write ad. No ad for bid response id: ' + id);
}
}
}
function requestAdFromPrebid() {
var message = JSON.stringify({
message: 'Prebid Request',
adId: '%%PATTERN:hb_adid%%'
});
window.parent.postMessage(message, publisherDomain);
}
function listenAdFromPrebid() {
window.addEventListener('message', renderAd, false);
}
listenAdFromPrebid();
requestAdFromPrebid();
</script>