-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathfriendly-iframe-embed.js
898 lines (815 loc) · 25.2 KB
/
friendly-iframe-embed.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {CommonSignals} from './common-signals';
import {FIE_EMBED_PROP} from './iframe-helper';
import {LEGACY_ELEMENTS, stubLegacyElements} from './service/extensions-impl';
import {Observable} from './observable';
import {Services} from './services';
import {Signals} from './utils/signals';
import {cssText as ampSharedCss} from '../build/ampshared.css';
import {
copyElementToChildWindow,
stubElementIfNotKnown,
upgradeOrRegisterElement,
} from './service/custom-element-registry';
import {dev, rethrowAsync, userAssert} from './log';
import {
disposeServicesForEmbed,
getAmpdoc,
getTopWindow,
installServiceInEmbedIfEmbeddable,
setParentWindow,
} from './service';
import {escapeHtml} from './dom';
import {installAmpdocServices} from './service/core-services';
import {install as installCustomElements} from './polyfills/custom-elements';
import {install as installDOMTokenList} from './polyfills/domtokenlist';
import {install as installDocContains} from './polyfills/document-contains';
import {installStylesForDoc, installStylesLegacy} from './style-installer';
import {installTimerInEmbedWindow} from './service/timer-impl';
import {isDocumentReady} from './document-ready';
import {isInAmpdocFieExperiment} from './ampdoc-fie';
import {layoutRectLtwh, moveLayoutRect} from './layout-rect';
import {loadPromise} from './event-helper';
import {
px,
resetStyles,
setImportantStyles,
setStyle,
setStyles,
} from './style';
import {toWin} from './types';
import {whenContentIniLoad} from './ini-load';
/**
* Parameters used to create the new "friendly iframe" embed.
* - html: The complete content of an AMP embed, which is itself an AMP
* document. Can include whatever is normally allowed in an AMP document,
* except for AMP `<script>` declarations. Those should be passed as an
* array of `extensionIds`.
* - extensionsIds: An optional array of AMP extension IDs used in this embed.
* - fonts: An optional array of fonts used in this embed.
*
* @typedef {{
* host: (?AmpElement|undefined),
* url: string,
* html: string,
* extensionIds: (?Array<string>|undefined),
* fonts: (?Array<string>|undefined),
* }}
*/
export let FriendlyIframeSpec;
/**
* @type {boolean|undefined}
* @visibleForTesting
*/
let srcdocSupported;
/**
* @param {boolean|undefined} val
* @visibleForTesting
*/
export function setSrcdocSupportedForTesting(val) {
srcdocSupported = val;
}
/**
* Returns `true` if the Friendly Iframes are supported.
* @return {boolean}
*/
function isSrcdocSupported() {
if (srcdocSupported === undefined) {
srcdocSupported = 'srcdoc' in HTMLIFrameElement.prototype;
}
return srcdocSupported;
}
/**
* Sets whether the embed is currently visible. The interpretation of visibility
* is up to the embed parent. However, most of typical cases would rely on
* whether the embed is currently in the viewport.
* @param {!FriendlyIframeEmbed} embed
* @param {boolean} visible
* TODO(dvoytenko): Re-evaluate and probably drop once layers are ready.
*/
export function setFriendlyIframeEmbedVisible(embed, visible) {
embed.setVisible_(visible);
}
/**
* Creates the requested "friendly iframe" embed. Returns the promise that
* will be resolved as soon as the embed is available. The actual
* initialization of the embed will start as soon as the `iframe` is added
* to the DOM.
* @param {!HTMLIFrameElement} iframe
* @param {!Element} container
* @param {!FriendlyIframeSpec} spec
* @param {function(!Window, ?./service/ampdoc-impl.AmpDoc=)=} opt_preinstallCallback
* @return {!Promise<!FriendlyIframeEmbed>}
*/
export function installFriendlyIframeEmbed(
iframe,
container,
spec,
opt_preinstallCallback // TODO(#22733): remove "window" argument.
) {
/** @const {!Window} */
const win = getTopWindow(toWin(iframe.ownerDocument.defaultView));
/** @const {!./service/extensions-impl.Extensions} */
const extensions = Services.extensionsFor(win);
const ampdocFieExperimentOn = isInAmpdocFieExperiment(win);
/** @const {?./service/ampdoc-impl.AmpDocService} */
const ampdocService = ampdocFieExperimentOn
? Services.ampdocServiceFor(win)
: null;
setStyle(iframe, 'visibility', 'hidden');
iframe.setAttribute('referrerpolicy', 'unsafe-url');
iframe.setAttribute('marginheight', '0');
iframe.setAttribute('marginwidth', '0');
// Pre-load extensions.
if (spec.extensionIds) {
spec.extensionIds.forEach(extensionId =>
extensions.preloadExtension(extensionId)
);
}
const html = mergeHtml(spec);
// Receive the signal when iframe is ready: it's document is formed.
iframe.onload = () => {
// Chrome does not reflect the iframe readystate.
iframe.readyState = 'complete';
};
const registerViolationListener = () => {
iframe.contentWindow.addEventListener(
'securitypolicyviolation',
violationEvent => {
dev().warn('FIE', 'security policy violation', violationEvent);
}
);
};
let loadedPromise;
if (isSrcdocSupported()) {
iframe.srcdoc = html;
loadedPromise = loadPromise(iframe);
container.appendChild(iframe);
registerViolationListener();
} else {
iframe.src = 'about:blank';
container.appendChild(iframe);
const childDoc = iframe.contentWindow.document;
childDoc.open();
registerViolationListener();
childDoc.write(html);
// With document.write, `iframe.onload` arrives almost immediately, thus
// we need to wait for child's `window.onload`.
loadedPromise = loadPromise(iframe.contentWindow);
childDoc.close();
}
// Wait for document ready signal.
// This is complicated due to crbug.com/649201 on Chrome and a similar issue
// on Safari where newly created document's `readyState` immediately equals
// `complete`, even though the document itself is not yet available. There's
// no other reliable signal for `readyState` in a child window and thus
// we have to fallback to polling.
let readyPromise;
if (isIframeReady(iframe)) {
readyPromise = Promise.resolve();
} else {
readyPromise = new Promise(resolve => {
/** @const {number} */
const interval = win.setInterval(() => {
if (isIframeReady(iframe)) {
resolve();
win.clearInterval(interval);
}
}, /* milliseconds */ 5);
// For safety, make sure we definitely stop polling when child doc is
// loaded.
loadedPromise
.catch(error => {
rethrowAsync(error);
})
.then(() => {
resolve();
win.clearInterval(interval);
});
});
}
return readyPromise.then(() => {
const childWin = /** @type {!Window} */ (iframe.contentWindow);
const signals = spec.host && spec.host.signals();
const ampdoc =
ampdocFieExperimentOn && ampdocService
? ampdocService.installFieDoc(spec.url, childWin, {signals})
: null;
const embed = new FriendlyIframeEmbed(iframe, spec, loadedPromise, ampdoc);
iframe[FIE_EMBED_PROP] = embed;
// Add extensions.
if (ampdoc && ampdocFieExperimentOn) {
embed.installExtensionsInFie(
extensions,
ampdoc,
spec.extensionIds || [],
opt_preinstallCallback
);
} else {
embed.installExtensionsInChildWindow(
extensions,
childWin,
spec.extensionIds || [],
opt_preinstallCallback
);
}
// Ready to be shown.
embed.startRender_();
return embed;
});
}
/**
* Returns `true` when iframe is ready.
* @param {!HTMLIFrameElement} iframe
* @return {boolean}
*/
function isIframeReady(iframe) {
// This is complicated due to crbug.com/649201 on Chrome and a similar issue
// on Safari where newly created document's `readyState` immediately equals
// `complete`, even though the document itself is not yet available. There's
// no other reliable signal for `readyState` in a child window and thus
// the best way to check is to see the contents of the body.
const childDoc = iframe.contentWindow && iframe.contentWindow.document;
return !!(
childDoc &&
isDocumentReady(childDoc) &&
childDoc.body &&
childDoc.body.firstChild
);
}
/**
* Merges base and fonts into html document.
* @param {!FriendlyIframeSpec} spec
* @return {string}
*/
function mergeHtml(spec) {
const originalHtml = spec.html;
const originalHtmlUp = originalHtml.toUpperCase();
// Find the insertion point.
let ip = originalHtmlUp.indexOf('<HEAD');
if (ip != -1) {
ip = originalHtmlUp.indexOf('>', ip + 1) + 1;
}
if (ip == -1) {
ip = originalHtmlUp.indexOf('<BODY');
}
if (ip == -1) {
ip = originalHtmlUp.indexOf('<HTML');
if (ip != -1) {
ip = originalHtmlUp.indexOf('>', ip + 1) + 1;
}
}
const result = [];
// Preambule.
if (ip > 0) {
result.push(originalHtml.substring(0, ip));
}
// Add <BASE> tag.
result.push(`<base href="${escapeHtml(spec.url)}">`);
// Load fonts.
if (spec.fonts) {
spec.fonts.forEach(font => {
result.push(
`<link href="${escapeHtml(font)}" rel="stylesheet" type="text/css">`
);
});
}
// Load CSP
result.push(
'<meta http-equiv=Content-Security-Policy ' +
"content=\"script-src 'none';object-src 'none';child-src 'none'\">"
);
// Postambule.
if (ip > 0) {
result.push(originalHtml.substring(ip));
} else {
result.push(originalHtml);
}
return result.join('');
}
/**
* Exposes `mergeHtml` for testing purposes.
* @param {!FriendlyIframeSpec} spec
* @return {string}
* @visibleForTesting
*/
export function mergeHtmlForTesting(spec) {
return mergeHtml(spec);
}
/**
* A "friendly iframe" embed. This is the iframe that's fully accessible to
* the AMP runtime. It's similar to Shadow DOM in many respects, but it also
* provides iframe/viewport measurements and enables the use of `vh`, `vw` and
* `@media` CSS.
*
* The friendly iframe is managed by the top-level AMP Runtime. When it's
* destroyed, the `destroy` method must be called to free up the shared
* resources.
*
* @visibleForTesting
*/
export class FriendlyIframeEmbed {
/**
* @param {!HTMLIFrameElement} iframe
* @param {!FriendlyIframeSpec} spec
* @param {!Promise} loadedPromise
* @param {?./service/ampdoc-impl.AmpDocFie} ampdoc
*/
constructor(iframe, spec, loadedPromise, ampdoc) {
/** @const {!HTMLIFrameElement} */
this.iframe = iframe;
/** @const {!Window} */
this.win = /** @type {!Window} */ (iframe.contentWindow);
/** @const {?./service/ampdoc-impl.AmpDocFie} */
this.ampdoc = ampdoc;
/** @const {!FriendlyIframeSpec} */
this.spec = spec;
/** @const {?AmpElement} */
this.host = spec.host || null;
/** @const @private {time} */
this.startTime_ = Date.now();
/**
* Starts out as invisible. The interpretation of this flag is up to
* the emded parent.
* @private {boolean}
*/
this.visible_ = false;
/** @private {!Observable<boolean>} */
this.visibilityObservable_ = new Observable();
/** @private @const */
this.signals_ = this.ampdoc
? this.ampdoc.signals()
: this.host
? this.host.signals()
: new Signals();
/** @private @const {!Promise} */
this.winLoadedPromise_ = Promise.all([loadedPromise, this.whenReady()]);
if (this.ampdoc) {
this.whenReady().then(() => this.ampdoc.setReady());
}
}
/**
* Ensures that all resources from this iframe have been released.
*/
destroy() {
this.removeResources_();
disposeServicesForEmbed(this.win);
if (this.ampdoc) {
this.ampdoc.dispose();
}
}
/**
* @return {time}
*/
getStartTime() {
return this.startTime_;
}
/**
* Returns the base URL for the embedded document.
* @return {string}
*/
getUrl() {
return this.spec.url;
}
/** @return {!Signals} */
signals() {
return this.signals_;
}
/**
* Returns a promise that will resolve when the embed document is ready.
* Notice that this signal coincides with the embed's `render-start`.
* @return {!Promise}
*/
whenReady() {
return this.signals_.whenSignal(CommonSignals.RENDER_START);
}
/**
* Returns a promise that will resolve when the child window's `onload` event
* has been emitted. In friendly iframes this typically only includes font
* loading.
* @return {!Promise}
*/
whenWindowLoaded() {
return this.winLoadedPromise_;
}
/**
* Returns a promise that will resolve when the initial load of the embed's
* content has been completed.
* @return {!Promise}
*/
whenIniLoaded() {
return this.signals_.whenSignal(CommonSignals.INI_LOAD);
}
/**
* @private
* @restricted
*/
startRender_() {
if (this.host) {
this.host.renderStarted();
} else {
this.signals_.signal(CommonSignals.RENDER_START);
}
// Common signal RENDER_START indicates time to toggle visibility
setStyle(this.iframe, 'visibility', '');
if (this.win.document && this.win.document.body) {
this.win.document.documentElement.classList.add('i-amphtml-fie');
setStyles(dev().assertElement(this.win.document.body), {
opacity: 1,
visibility: 'visible',
animation: 'none',
});
}
// Initial load signal signal.
let rect;
if (this.host) {
rect = this.host.getLayoutBox();
} else {
rect = layoutRectLtwh(
0,
0,
this.win./*OK*/ innerWidth,
this.win./*OK*/ innerHeight
);
}
Promise.all([
this.whenReady(),
whenContentIniLoad(this.iframe, this.win, rect),
]).then(() => {
this.signals_.signal(CommonSignals.INI_LOAD);
});
}
/**
* Whether the embed is currently visible. The interpretation of visibility
* is up to the embed parent. However, most of typical cases would rely on
* whether the embed is currently in the viewport.
* @return {boolean}
* TODO(dvoytenko): Re-evaluate and probably drop once layers are ready.
*/
isVisible() {
return this.visible_;
}
/**
* See `isVisible` for more info.
* @param {function(boolean)} handler
* @return {!UnlistenDef}
*/
onVisibilityChanged(handler) {
return this.visibilityObservable_.add(handler);
}
/**
* @param {boolean} visible
* @private
* @restricted
*/
setVisible_(visible) {
if (this.visible_ != visible) {
this.visible_ = visible;
this.visibilityObservable_.fire(this.visible_);
}
}
/**
* @return {!HTMLBodyElement}
* @visibleForTesting
*/
getBodyElement() {
return /** @type {!HTMLBodyElement} */ ((
this.iframe.contentDocument || this.iframe.contentWindow.document
).body);
}
/**
* @return {!./service/resources-interface.ResourcesInterface}
* @private
*/
getResources_() {
return Services.resourcesForDoc(this.iframe);
}
/**
* @return {!./service/mutator-interface.MutatorInterface}
* @private
*/
getMutator_() {
return Services.mutatorForDoc(this.iframe);
}
/**
* Runs a measure/mutate cycle ensuring that the iframe change is propagated
* to the resource manager.
* @param {{measure: (function()|undefined), mutate: function()}} task
* @return {!Promise}
* @private
*/
measureMutate_(task) {
return this.getMutator_().measureMutateElement(
this.iframe,
task.measure || null,
task.mutate
);
}
/**
* Removes all resources belonging to the FIE window.
* @private
*/
removeResources_() {
const resources = this.getResources_();
const toRemove = resources
.get()
.filter(resource => resource.hostWin == this.win);
toRemove.forEach(resource => {
resources.remove(resource.element);
resource.disconnect();
});
}
/**
* @return {!Promise}
*/
enterFullOverlayMode() {
const ampAdParent = dev().assertElement(this.iframe.parentNode);
// Security assertion. Otherwise any 3p frame could request lighbox mode.
userAssert(
ampAdParent.tagName.toLowerCase() == 'amp-ad',
'Only <amp-ad> is allowed to enter lightbox mode.'
);
let bodyStyle;
return this.measureMutate_({
measure: () => {
const rect = this.host
? this.host.getLayoutBox()
: this.iframe./*OK*/ getBoundingClientRect();
// Offset by scroll top as iframe will be position: fixed.
const dy = -Services.viewportForDoc(this.iframe).getScrollTop();
const {top, left, width, height} = moveLayoutRect(rect, /* dx */ 0, dy);
// Offset body by header height to prevent visual jump.
bodyStyle = {
top: px(top),
left: px(left),
width: px(width),
height: px(height),
};
},
mutate: () => {
// !important to prevent abuse e.g. box @ ltwh = 0, 0, 0, 0
setImportantStyles(this.iframe, {
'position': 'fixed',
'left': 0,
'right': 0,
'bottom': 0,
'width': '100vw',
'top': 0,
'height': '100vh',
});
// We need to override runtime-level !important rules
setImportantStyles(this.getBodyElement(), {
'background': 'transparent',
'position': 'absolute',
'bottom': 'auto',
'right': 'auto',
// Read during vsync measure phase.
'top': bodyStyle.top,
'left': bodyStyle.left,
'width': bodyStyle.width,
'height': bodyStyle.height,
});
},
});
}
/**
* @return {!Promise}
*/
leaveFullOverlayMode() {
return this.measureMutate_({
mutate: () => {
resetStyles(this.iframe, [
'position',
'left',
'right',
'top',
'bottom',
'width',
'height',
]);
// we're not resetting background here as we need to set it to
// transparent permanently.
resetStyles(this.getBodyElement(), [
'position',
'top',
'left',
'width',
'height',
'bottom',
'right',
]);
},
});
}
/**
* Install extensions in the child window (friendly iframe). The pre-install
* callback, if specified, is executed after polyfills have been configured
* but before the first extension is installed.
* @param {!./service/extensions-impl.Extensions} extensions
* @param {!./service/ampdoc-impl.AmpDocFie} ampdoc
* @param {!Array<string>} extensionIds
* @param {function(!Window, ?./service/ampdoc-impl.AmpDoc=)=} opt_preinstallCallback
* @return {!Promise}
* @visibleForTesting
*/
installExtensionsInFie(
extensions,
ampdoc,
extensionIds,
opt_preinstallCallback
) {
const topWin = extensions.win;
const childWin = ampdoc.win;
const parentWin = toWin(childWin.frameElement.ownerDocument.defaultView);
setParentWindow(childWin, parentWin);
// Install necessary polyfills.
installPolyfillsInChildWindow(parentWin, childWin);
// Install runtime styles.
installStylesForDoc(
ampdoc,
ampSharedCss,
/* callback */ null,
/* opt_isRuntimeCss */ true,
/* opt_ext */ 'amp-runtime'
);
// Run pre-install callback.
if (opt_preinstallCallback) {
opt_preinstallCallback(ampdoc.win, ampdoc);
}
// Install embeddable standard services.
installStandardServicesInEmbeddedDoc(ampdoc);
// Install built-ins and legacy elements.
copyBuiltinElementsToChildWindow(topWin, childWin);
stubLegacyElements(childWin);
return Promise.all(
extensionIds.map(extensionId => {
// This will extend automatic upgrade of custom elements from top
// window to the child window.
if (!LEGACY_ELEMENTS.includes(extensionId)) {
stubElementIfNotKnown(childWin, extensionId);
}
return extensions.installExtensionInDoc(ampdoc, extensionId);
})
);
}
/**
* Install extensions in the child window (friendly iframe). The pre-install
* callback, if specified, is executed after polyfills have been configured
* but before the first extension is installed.
* @param {!./service/extensions-impl.Extensions} extensions
* @param {!Window} childWin
* @param {!Array<string>} extensionIds
* @param {function(!Window, ?./service/ampdoc-impl.AmpDoc=)=} opt_preinstallCallback
* @return {!Promise}
* @visibleForTesting
*/
installExtensionsInChildWindow(
extensions,
childWin,
extensionIds,
opt_preinstallCallback
) {
const topWin = extensions.win;
const parentWin = toWin(childWin.frameElement.ownerDocument.defaultView);
setParentWindow(childWin, parentWin);
// Install necessary polyfills.
installPolyfillsInChildWindow(parentWin, childWin);
// Install runtime styles.
installStylesLegacy(
childWin.document,
ampSharedCss,
/* callback */ null,
/* opt_isRuntimeCss */ true,
/* opt_ext */ 'amp-runtime'
);
// Run pre-install callback.
if (opt_preinstallCallback) {
opt_preinstallCallback(childWin);
}
// Install embeddable standard services.
installStandardServicesInEmbed(childWin);
// Install built-ins and legacy elements.
copyBuiltinElementsToChildWindow(topWin, childWin);
stubLegacyElements(childWin);
const promises = [];
extensionIds.forEach(extensionId => {
// This will extend automatic upgrade of custom elements from top
// window to the child window.
if (!LEGACY_ELEMENTS.includes(extensionId)) {
stubElementIfNotKnown(childWin, extensionId);
}
// Install CSS.
const promise = extensions
.preloadExtension(extensionId)
.then(extension => {
// Adopt embeddable extension services.
extension.services.forEach(service => {
installServiceInEmbedIfEmbeddable(childWin, service.serviceClass);
});
// Adopt the custom elements.
let elementPromises = null;
for (const elementName in extension.elements) {
const elementDef = extension.elements[elementName];
const elementPromise = new Promise(resolve => {
if (elementDef.css) {
installStylesLegacy(
childWin.document,
elementDef.css,
/* completeCallback */ resolve,
/* isRuntime */ false,
extensionId
);
} else {
resolve();
}
}).then(() => {
upgradeOrRegisterElement(
childWin,
elementName,
elementDef.implementationClass
);
});
if (elementPromises) {
elementPromises.push(elementPromise);
} else {
elementPromises = [elementPromise];
}
}
if (elementPromises) {
return Promise.all(elementPromises).then(() => extension);
}
return extension;
});
promises.push(promise);
});
return Promise.all(promises);
}
}
/**
* Install polyfills in the child window (friendly iframe).
* @param {!Window} parentWin
* @param {!Window} childWin
*/
function installPolyfillsInChildWindow(parentWin, childWin) {
installDocContains(childWin);
installDOMTokenList(childWin);
// The anonymous class parameter allows us to detect native classes vs
// transpiled classes.
installCustomElements(childWin, class {});
}
/**
* Copy builtins to a child window.
* @param {!Window} parentWin
* @param {!Window} childWin
*/
function copyBuiltinElementsToChildWindow(parentWin, childWin) {
copyElementToChildWindow(parentWin, childWin, 'amp-img');
copyElementToChildWindow(parentWin, childWin, 'amp-pixel');
}
/**
* Adopt predefined core services for the embedded ampdoc (friendly iframe).
* @param {!./service/ampdoc-impl.AmpDoc} ampdoc
*/
function installStandardServicesInEmbeddedDoc(ampdoc) {
installAmpdocServices(ampdoc);
installTimerInEmbedWindow(ampdoc.win);
}
/**
* Adopt predefined core services for the child window (friendly iframe).
* @param {!Window} childWin
* @visibleForTesting
*/
export function installStandardServicesInEmbed(childWin) {
// TODO(#22733): remove when ampdoc-fie is launched.
const frameElement = dev().assertElement(
childWin.frameElement,
'frameElement not found for embed'
);
const standardServices = [
// The order of service adoptations is important.
Services.urlForDoc(frameElement),
Services.actionServiceForDoc(frameElement),
Services.standardActionsForDoc(frameElement),
Services.navigationForDoc(frameElement),
];
const ampdoc = getAmpdoc(frameElement);
standardServices.forEach(service => {
// Static functions must be invoked on the class, not the instance.
service.constructor.installInEmbedWindow(childWin, ampdoc);
});
installTimerInEmbedWindow(childWin);
}