Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: add location method for cross-frame creatives and update creatives #11863

Merged
merged 2 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion creative/constants.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// eslint-disable-next-line prebid/validate-imports
import { AD_RENDER_FAILED_REASON, EVENTS, MESSAGES } from '../src/constants.js';
import {AD_RENDER_FAILED_REASON, EVENTS, MESSAGES} from '../src/constants.js';

export {PB_LOCATOR} from '../src/constants.js';
export const MESSAGE_REQUEST = MESSAGES.REQUEST;
export const MESSAGE_RESPONSE = MESSAGES.RESPONSE;
export const MESSAGE_EVENT = MESSAGES.EVENT;
Expand Down
20 changes: 16 additions & 4 deletions creative/crossDomain.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import {
ERROR_EXCEPTION,
EVENT_AD_RENDER_FAILED, EVENT_AD_RENDER_SUCCEEDED,
EVENT_AD_RENDER_FAILED,
EVENT_AD_RENDER_SUCCEEDED,
MESSAGE_EVENT,
MESSAGE_REQUEST,
MESSAGE_RESPONSE
MESSAGE_RESPONSE,
PB_LOCATOR
} from './constants.js';

const mkFrame = (() => {
Expand All @@ -24,14 +26,24 @@ const mkFrame = (() => {
};
})();

function isPrebidWindow(win) {
return !!win.frames[PB_LOCATOR];
}

export function renderer(win) {
let target = win.parent;
while (target !== win.top && !isPrebidWindow(target)) {
target = target.parent;
}
if (!isPrebidWindow(target)) target = win.parent;

return function ({adId, pubUrl, clickUrl}) {
const pubDomain = new URL(pubUrl, window.location).origin;

function sendMessage(type, payload, responseListener) {
const channel = new MessageChannel();
channel.port1.onmessage = guard(responseListener);
win.parent.postMessage(JSON.stringify(Object.assign({message: type, adId}, payload)), pubDomain, [channel.port2]);
target.postMessage(JSON.stringify(Object.assign({message: type, adId}, payload)), pubDomain, [channel.port2]);
}

function onError(e) {
Expand Down Expand Up @@ -77,7 +89,7 @@ export function renderer(win) {
W.Promise.resolve(W.render(data, {sendMessage, mkFrame}, win)).then(
() => sendMessage(MESSAGE_EVENT, {event: EVENT_AD_RENDER_SUCCEEDED}),
onError
)
);
});
win.document.body.appendChild(renderer);
}
Expand Down
2 changes: 1 addition & 1 deletion integrationExamples/gpt/x-domain/creative.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// creative will be rendered, e.g. GAM delivering a SafeFrame

// this code is autogenerated, also available in 'build/creative/creative.js'
<script>!function(){"use strict";const e="Prebid Event",n=(()=>{const e={frameBorder:0,scrolling:"no",marginHeight:0,marginWidth:0,topMargin:0,leftMargin:0,allowTransparency:"true"};return(n,t)=>{const r=n.createElement("iframe");return Object.entries(Object.assign({},t,e)).forEach((([e,n])=>r.setAttribute(e,n))),r}})();var t;window.pbRender=(t=window,function({adId:r,pubUrl:s,clickUrl:o}){const i=new URL(s,window.location).origin;function a(e,n,s){const o=new MessageChannel;o.port1.onmessage=d(s),t.parent.postMessage(JSON.stringify(Object.assign({message:e,adId:r},n)),i,[o.port2])}function c(n){a(e,{event:"adRenderFailed",info:{reason:n?.reason||"exception",message:n?.message}}),n?.stack&&console.error(n)}function d(e){return function(){try{return e.apply(this,arguments)}catch(e){c(e)}}}a("Prebid Request",{options:{clickUrl:o}},(function(s){let o;try{o=JSON.parse(s.data)}catch(e){return}if("Prebid Response"===o.message&&o.adId===r){const r=n(t.document,{width:0,height:0,style:"display: none",srcdoc:`<script>${o.renderer}<\/script>`});r.onload=d((function(){const s=r.contentWindow;s.Promise.resolve(s.render(o,{sendMessage:a,mkFrame:n},t)).then((()=>a(e,{event:"adRenderSucceeded"})),c)})),t.document.body.appendChild(r)}}))})}();</script>
<script>(()=>{"use strict";const e="Prebid Event",n=(()=>{const e={frameBorder:0,scrolling:"no",marginHeight:0,marginWidth:0,topMargin:0,leftMargin:0,allowTransparency:"true"};return(n,t)=>{const r=n.createElement("iframe");return Object.entries(Object.assign({},t,e)).forEach((([e,n])=>r.setAttribute(e,n))),r}})();function t(e){return!!e.frames.__pb_locator__}window.pbRender=function(r){let o=r.parent;for(;o!==r.top&&!t(o);)o=o.parent;return t(o)||(o=r.parent),function({adId:t,pubUrl:s,clickUrl:i}){const a=new URL(s,window.location).origin;function c(e,n,r){const s=new MessageChannel;s.port1.onmessage=l(r),o.postMessage(JSON.stringify(Object.assign({message:e,adId:t},n)),a,[s.port2])}function d(n){c(e,{event:"adRenderFailed",info:{reason:n?.reason||"exception",message:n?.message}}),n?.stack&&console.error(n)}function l(e){return function(){try{return e.apply(this,arguments)}catch(e){d(e)}}}c("Prebid Request",{options:{clickUrl:i}},(function(o){let s;try{s=JSON.parse(o.data)}catch(e){return}if("Prebid Response"===s.message&&s.adId===t){const t=n(r.document,{width:0,height:0,style:"display: none",srcdoc:`<script>${s.renderer}<\/script>`});t.onload=l((function(){const o=t.contentWindow;o.Promise.resolve(o.render(s,{sendMessage:c,mkFrame:n},r)).then((()=>c(e,{event:"adRenderSucceeded"})),d)})),r.document.body.appendChild(t)}}))}}(window)})();</script>

<script>
pbRender({
Expand Down
2 changes: 1 addition & 1 deletion libraries/creative-renderer-display/renderer.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion libraries/creative-renderer-native/renderer.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 25 additions & 2 deletions src/adRendering.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import {createIframe, deepAccess, inIframe, insertElement, logError, logWarn, replaceMacros} from './utils.js';
import {
createIframe,
createInvisibleIframe,
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 {AD_RENDER_FAILED_REASON, BID_STATUS, EVENTS, MESSAGES, PB_LOCATOR} from './constants.js';
import {config} from './config.js';
import {executeRenderer, isRendererRequired} from './Renderer.js';
import {VIDEO} from './mediaTypes.js';
Expand Down Expand Up @@ -235,3 +244,17 @@ export function renderAdDirect(doc, adId, options) {
fail(EXCEPTION, e.message);
}
}

/**
* Insert an invisible, named iframe that can be used by creatives to locate the window Prebid is running in
* (by looking for one that has `.frames[PB_LOCATOR]` defined).
* This is necessary because in some situations creatives may be rendered inside nested iframes - Prebid is not necessarily
* in the immediate parent window.
*/
export function insertLocatorFrame() {
if (!window.frames[PB_LOCATOR]) {
const frame = createInvisibleIframe();
frame.name = PB_LOCATOR;
document.body.appendChild(frame);
}
}
2 changes: 2 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,5 @@ export const MESSAGES = {
NATIVE: 'Prebid Native',
EVENT: 'Prebid Event'
};

export const PB_LOCATOR = '__pb_locator__';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very cool :)

3 changes: 2 additions & 1 deletion src/prebid.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {newMetrics, useMetrics} from './utils/perfMetrics.js';
import {defer, GreedyPromise} from './utils/promise.js';
import {enrichFPD} from './fpd/enrichment.js';
import {allConsent} from './consentHandler.js';
import {renderAdDirect} from './adRendering.js';
import {insertLocatorFrame, renderAdDirect} from './adRendering.js';
import {getHighestCpm} from './utils/reducers.js';
import {fillVideoDefaults} from './video.js';

Expand Down Expand Up @@ -976,6 +976,7 @@ function processQueue(queue) {
* @alias module:pbjs.processQueue
*/
pbjsInstance.processQueue = function () {
insertLocatorFrame();
hook.ready();
processQueue(pbjsInstance.que);
processQueue(pbjsInstance.cmd);
Expand Down
40 changes: 38 additions & 2 deletions test/spec/creative/crossDomainCreative_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@ import {

describe('cross-domain creative', () => {
const ORIGIN = 'https://example.com';
let win, renderAd, messages, mkIframe;
let win, top, renderAd, messages, mkIframe;

beforeEach(() => {
messages = [];
mkIframe = sinon.stub();
top = {
frames: {}
};
top.top = top;
win = {
top,
frames: {},
document: {
body: {
appendChild: sinon.stub(),
Expand All @@ -30,12 +36,14 @@ describe('cross-domain creative', () => {
})
},
parent: {
parent: top,
frames: {'__pb_locator__': {}},
postMessage: sinon.stub().callsFake((payload, targetOrigin, transfer) => {
messages.push({payload: JSON.parse(payload), targetOrigin, transfer});
})
}
};
renderAd = renderer(win);
renderAd = (...args) => renderer(win)(...args);
})

function waitFor(predicate, timeout = 1000) {
Expand Down Expand Up @@ -64,6 +72,34 @@ describe('cross-domain creative', () => {
expect(messages[0].targetOrigin).to.eql('https://domain.com:123')
});

it('posts to first parent if no __pb_locator__ can be found', () => {
delete win.parent.frames['__pb_locator__'];
renderAd({pubUrl: 'https://www.example.com'});
expect(messages.length).to.eql(1);
})

describe('when there are multiple ancestors', () => {
let target;
beforeEach(() => {
target = win.parent;
win.parent = {
top,
frames: {},
parent: {
...target,
parent: {
frames: {'__pb_locator__': {}},
top
}
}
}
})
it('posts message to the first ancestor with __pb_locator__ child', () => {
renderAd({pubUrl: 'https://www.example.com'});
expect(messages.length).to.eql(1);
});
})

it('generates request message with adId and clickUrl', () => {
renderAd({adId: '123', clickUrl: 'https://click-url.com', pubUrl: ORIGIN});
expect(messages[0].payload).to.eql({
Expand Down
7 changes: 6 additions & 1 deletion test/spec/unit/pbjs_api_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {enrichFPD} from '../../../src/fpd/enrichment.js';
import {mockFpdEnrichments} from '../../helpers/fpd.js';
import {generateUUID} from '../../../src/utils.js';
import {getCreativeRenderer} from '../../../src/creativeRenderers.js';
import { BID_STATUS, EVENTS, GRANULARITY_OPTIONS, TARGETING_KEYS } from 'src/constants.js';
import {BID_STATUS, EVENTS, GRANULARITY_OPTIONS, PB_LOCATOR, TARGETING_KEYS} from 'src/constants.js';
import {getBidToRender} from '../../../src/adRendering.js';

var assert = require('chai').assert;
Expand Down Expand Up @@ -236,6 +236,11 @@ describe('Unit: Prebid Module', function () {
getBidToRender.getHooks({hook: getBidToRenderHook}).remove();
});

it('should insert a locator frame on the page', () => {
$$PREBID_GLOBAL$$.processQueue();
expect(window.frames[PB_LOCATOR]).to.exist;
})

describe('and global adUnits', () => {
const startingAdUnits = [
{
Expand Down