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

Convert ad iframes to get initialIntersection async #31753

Merged
merged 8 commits into from
Jan 14, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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: 1 addition & 2 deletions 3p/3d-gltf/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ export default class GltfViewer {
this.ampPlay_ = true;

/** @private */
this.ampInViewport_ =
options['initialIntersection']['intersectionRatio'] > 0;
this.ampInViewport_ = false;
dvoytenko marked this conversation as resolved.
Show resolved Hide resolved

/** @private */
this.setSize_ = this.setupSize_();
Expand Down
53 changes: 35 additions & 18 deletions extensions/amp-a4a/0.1/amp-a4a.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ import {
isSrcdocSupported,
} from '../../../src/friendly-iframe-embed';
import {installUrlReplacementsForEmbed} from '../../../src/service/url-replacements-impl';
import {
intersectionEntryToJson,
measureIntersection,
} from '../../../src/utils/intersection';
import {isAdPositionAllowed} from '../../../src/ad-helper';
import {isArray, isEnumValue, isObject} from '../../../src/types';
import {listenOnce} from '../../../src/event-helper';
Expand Down Expand Up @@ -2041,14 +2045,22 @@ export class AmpA4A extends AMP.BaseElement {
*/
renderViaIframeGet_(adUrl) {
this.maybeTriggerAnalyticsEvent_('renderCrossDomainStart');
return this.iframeRenderHelper_(
dict({
'src': Services.xhrFor(this.win).getCorsUrl(this.win, adUrl),
'name': JSON.stringify(
getContextMetadata(this.win, this.element, this.sentinel)
),
})
const contextMetadata = getContextMetadata(
this.win,
this.element,
this.sentinel
);
return measureIntersection(this.element).then((intersection) => {
samouri marked this conversation as resolved.
Show resolved Hide resolved
contextMetadata['_context'][
'initialIntersection'
] = intersectionEntryToJson(intersection);
return this.iframeRenderHelper_(
dict({
'src': Services.xhrFor(this.win).getCorsUrl(this.win, adUrl),
'name': JSON.stringify(contextMetadata),
})
);
});
}

/**
Expand Down Expand Up @@ -2114,17 +2126,22 @@ export class AmpA4A extends AMP.BaseElement {
this.sentinel,
this.getAdditionalContextMetadata(method == XORIGIN_MODE.SAFEFRAME)
);
// TODO(bradfrizzell) Clean up name assigning.
if (method == XORIGIN_MODE.NAMEFRAME) {
contextMetadata['creative'] = creative;
name = JSON.stringify(contextMetadata);
} else if (method == XORIGIN_MODE.SAFEFRAME) {
contextMetadata = JSON.stringify(contextMetadata);
name =
`${this.safeframeVersion};${creative.length};${creative}` +
`${contextMetadata}`;
}
return this.iframeRenderHelper_(dict({'src': srcPath, 'name': name}));
return measureIntersection(this.element).then((intersection) => {
contextMetadata['initialIntersection'] = intersectionEntryToJson(
intersection
);
if (method == XORIGIN_MODE.NAMEFRAME) {
contextMetadata['creative'] = creative;
name = JSON.stringify(contextMetadata);
} else if (method == XORIGIN_MODE.SAFEFRAME) {
contextMetadata = JSON.stringify(contextMetadata);
name =
`${this.safeframeVersion};${creative.length};${creative}` +
`${contextMetadata}`;
}

return this.iframeRenderHelper_(dict({'src': srcPath, 'name': name}));
});
});
}

Expand Down
52 changes: 30 additions & 22 deletions extensions/amp-a4a/0.1/name-frame-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import {createElementWithAttributes} from '../../../src/dom';
import {dict} from '../../../src/utils/object';
import {getContextMetadata} from '../../../src/iframe-attributes';
import {getDefaultBootstrapBaseUrl} from '../../../src/3p-frame';
import {
intersectionEntryToJson,
measureIntersection,
} from '../../../src/utils/intersection';
import {utf8Decode} from '../../../src/utils/bytes';

/**
Expand Down Expand Up @@ -50,28 +54,32 @@ export class NameFrameRenderer extends Renderer {
crossDomainData.additionalContextMetadata
);
contextMetadata['creative'] = creative;
const attributes = dict({
'src': srcPath,
'name': JSON.stringify(contextMetadata),
'height': context.size.height,
'width': context.size.width,
'frameborder': '0',
'allowfullscreen': '',
'allowtransparency': '',
'scrolling': 'no',
'marginwidth': '0',
'marginheight': '0',
return measureIntersection(element).then((intersection) => {
contextMetadata['_context'][
'initialIntersection'
] = intersectionEntryToJson(intersection);
const attributes = dict({
'src': srcPath,
'name': JSON.stringify(contextMetadata),
'height': context.size.height,
'width': context.size.width,
'frameborder': '0',
'allowfullscreen': '',
'allowtransparency': '',
'scrolling': 'no',
'marginwidth': '0',
'marginheight': '0',
});
if (crossDomainData.sentinel) {
attributes['data-amp-3p-sentinel'] = crossDomainData.sentinel;
}
const iframe = createElementWithAttributes(
/** @type {!Document} */ (element.ownerDocument),
'iframe',
/** @type {!JsonObject} */ (attributes)
);
// TODO(glevitzky): Ensure that applyFillContent or equivalent is called.
element.appendChild(iframe);
});
if (crossDomainData.sentinel) {
attributes['data-amp-3p-sentinel'] = crossDomainData.sentinel;
}
const iframe = createElementWithAttributes(
/** @type {!Document} */ (element.ownerDocument),
'iframe',
/** @type {!JsonObject} */ (attributes)
);
// TODO(glevitzky): Ensure that applyFillContent or equivalent is called.
element.appendChild(iframe);
return Promise.resolve();
}
}
9 changes: 6 additions & 3 deletions extensions/amp-a4a/0.1/test/test-name-frame-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ describes.realWin('NameFrameRenderer', realWinConfig, (env) => {
let context;
let creativeData;

beforeEach(() => {
beforeEach(async () => {
context = {
size: {width: '320', height: '50'},
requestUrl: 'http://www.google.com',
Expand All @@ -48,10 +48,13 @@ describes.realWin('NameFrameRenderer', realWinConfig, (env) => {
containerElement = env.win.document.createElement('div');
containerElement.setAttribute('height', 50);
containerElement.setAttribute('width', 320);
containerElement.getIntersectionChangeEntry = () => ({});
env.win.document.body.appendChild(containerElement);

new NameFrameRenderer().render(context, containerElement, creativeData);
await new NameFrameRenderer().render(
context,
containerElement,
creativeData
);
});

it('should append iframe child', () => {
Expand Down
29 changes: 19 additions & 10 deletions extensions/amp-ad/0.1/amp-ad-3p-impl.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ import {
getConsentPolicyState,
} from '../../../src/consent';
import {getIframe, preloadBootstrap} from '../../../src/3p-frame';
import {
intersectionEntryToJson,
measureIntersection,
} from '../../../src/utils/intersection';
import {moveLayoutRect} from '../../../src/layout-rect';
import {
observeWithSharedInOb,
Expand Down Expand Up @@ -407,16 +411,21 @@ export class AmpAd3PImpl extends AMP.BaseElement {
// because both happen inside a cross-domain iframe. Separating them
// here, though, allows us to measure the impact of ad throttling via
// incrementLoadingAds().
const iframe = getIframe(
toWin(this.element.ownerDocument.defaultView),
this.element,
this.type_,
opt_context,
{disallowCustom: this.config.remoteHTMLDisabled}
);
iframe.title = this.element.title || 'Advertisement';
this.xOriginIframeHandler_ = new AmpAdXOriginIframeHandler(this);
return this.xOriginIframeHandler_.init(iframe);
return measureIntersection(this.element).then((intersection) => {
const iframe = getIframe(
toWin(this.element.ownerDocument.defaultView),
this.element,
this.type_,
opt_context,
{
disallowCustom: this.config.remoteHTMLDisabled,
initialIntersection: intersectionEntryToJson(intersection),
}
);
iframe.title = this.element.title || 'Advertisement';
this.xOriginIframeHandler_ = new AmpAdXOriginIframeHandler(this);
return this.xOriginIframeHandler_.init(iframe);
});
})
.then(() => {
observeWithSharedInOb(this.element, (inViewport) =>
Expand Down
32 changes: 1 addition & 31 deletions extensions/amp-ad/0.1/legacy-ad-intersection-observer-host.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {Services} from '../../../src/services';
import {SubscriptionApi} from '../../../src/iframe-helper';
import {devAssert} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {intersectionEntryToJson} from '../../../src/utils/intersection';
import {
layoutRectLtwh,
moveLayoutRect,
Expand Down Expand Up @@ -319,34 +320,3 @@ export class LegacyAdIntersectionObserverHost {
this.postMessageApi_.destroy();
}
}

/**
* Convert a DOMRect to a regular object to make it serializable.
*
* @param {!DOMRect} domRect
* @return {!DOMRect}
*/
function domRectToJson(domRect) {
if (domRect == null) {
return domRect;
}

const {x, y, width, height, top, right, bottom, left} = domRect;
return {x, y, width, height, top, right, bottom, left};
}

/**
* Convert an IntersectionObserverEntry to a regular object to make it serializable.
*
* @param {!IntersectionObserverEntry} entry
* @return {!IntersectionObserverEntry}
*/
function intersectionEntryToJson(entry) {
return {
time: entry.time,
rootBounds: domRectToJson(entry.rootBounds),
boundingClientRect: domRectToJson(entry.boundingClientRect),
intersectionRect: domRectToJson(entry.intersectionRect),
intersectionRatio: entry.intersectionRatio,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ describes.sandboxed('IntersectionObserverHostForAd', {}, () => {
);
stubFireInOb(ioInstance);
insert(testIframe);
ioInstance.onViewportCallback_(true);
ioInstance.onViewportCallback_(getInObEntry());
expect(sendElementIntersectionSpy).to.be.calledOnce;
expect(onScrollSpy).to.be.calledOnce;
expect(onChangeSpy).to.be.calledOnce;
Expand All @@ -479,7 +479,7 @@ describes.sandboxed('IntersectionObserverHostForAd', {}, () => {
);
insert(testIframe);
ioInstance.onViewportCallback_(getInObEntry());
ioInstance.onViewportCallback_({intersectionRatio: false});
ioInstance.onViewportCallback_({...getInObEntry(), intersectionRatio: 0});
expect(sendElementIntersectionSpy).to.have.callCount(2);
expect(ioInstance.unlistenViewportChanges_).to.be.null;
});
Expand Down
11 changes: 10 additions & 1 deletion src/3p-frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ function getFrameAttributes(parentWindow, element, opt_type, opt_context) {
* @param {{
* disallowCustom: (boolean|undefined),
* allowFullscreen: (boolean|undefined),
* initialIntersection: (IntersectionObserverEntry|undefined),
* }=} options Options for the created iframe.
* @return {!HTMLIFrameElement} The iframe.
*/
Expand All @@ -78,7 +79,11 @@ export function getIframe(
opt_context,
options = {}
) {
const {disallowCustom = false, allowFullscreen = false} = options;
const {
disallowCustom = false,
allowFullscreen = false,
initialIntersection,
} = options;
// Check that the parentElement is already in DOM. This code uses a new and
// fast `isConnected` API and thus only used when it's available.
devAssert(
Expand All @@ -92,6 +97,10 @@ export function getIframe(
opt_type,
opt_context
);
if (initialIntersection) {
attributes['_context']['initialIntersection'] = initialIntersection;
}

const iframe = /** @type {!HTMLIFrameElement} */ (parentWindow.document.createElement(
'iframe'
));
Expand Down
1 change: 0 additions & 1 deletion src/iframe-attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ export function getContextMetadata(
'height': layoutRect.height,
}
: null,
'initialIntersection': element.getIntersectionChangeEntry(),
'domFingerprint': DomFingerprint.generate(element),
'experimentToggles': experimentToggles(parentWindow),
'sentinel': sentinel,
Expand Down
7 changes: 1 addition & 6 deletions test/integration/test-amp-ad-3p.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,11 @@ describe('amp-ad 3P', () => {
});
const {initialIntersection} = context;
expect(initialIntersection.rootBounds).to.deep.equal(
layoutRectLtwh(0, 0, 500, 3000)
layoutRectLtwh(0, 0, window.innerWidth, window.innerHeight)
);
expect(initialIntersection.boundingClientRect).to.deep.equal(
layoutRectLtwh(0, platform.isIos() ? 1001 : 1000, 300, 250)
);
expect(initialIntersection.intersectionRect).to.deep.equal(
layoutRectLtwh(0, platform.isIos() ? 1001 : 1000, 300, 250)
);
expect(initialIntersection.intersectionRatio).to.equal(1);
expect(initialIntersection.time).to.be.a('number');
expect(context.isMaster).to.exist;
expect(context.computeInMasterFrame).to.exist;
expect(context.location).to.deep.equal({
Expand Down
37 changes: 11 additions & 26 deletions test/unit/3p/test-3p-frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,6 @@ describes.realWin('3p-frame', {amp: true}, (env) => {
div.setAttribute('width', '50');
div.setAttribute('height', '100');

const {innerWidth: width, innerHeight: height} = window;
setupElementFunctions(div);

const viewer = Services.viewerForDoc(window.document);
Expand All @@ -190,7 +189,16 @@ describes.realWin('3p-frame', {amp: true}, (env) => {
.stub(WindowInterface, 'getLocation')
.returns({href: locationHref});

const iframe = getIframe(window, div, '_ping_', {clientId: 'cidValue'});
const initialIntersection = {test: 'testIntersection'};
const iframe = getIframe(
window,
div,
'_ping_',
{clientId: 'cidValue'},
{
initialIntersection,
}
);
const {src} = iframe;
const docInfo = Services.documentInfoForDoc(window.document);
expect(docInfo.pageViewId).to.not.be.empty;
Expand Down Expand Up @@ -230,30 +238,7 @@ describes.realWin('3p-frame', {amp: true}, (env) => {
'startTime': 1234567888,
'experimentToggles': {'exp-a': true, 'exp-b': true},
'sentinel': sentinel,
'initialIntersection': {
'time': 1234567888,
'rootBounds': {
'left': 0,
'top': 0,
'width': width,
'height': height,
'bottom': height,
'right': width,
'x': 0,
'y': 0,
},
'boundingClientRect': {'width': 100, 'height': 200},
'intersectionRect': {
'left': 0,
'top': 0,
'width': 0,
'height': 0,
'bottom': 0,
'right': 0,
'x': 0,
'y': 0,
},
},
initialIntersection,
},
};
expect(src).to.equal(
Expand Down