-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
iframe-transport.js
231 lines (212 loc) · 7.46 KB
/
iframe-transport.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
/**
* Copyright 2017 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 {createElementWithAttributes} from '../../../src/dom';
import {dev} from '../../../src/log';
import {getMode} from '../../../src/mode';
import {
calculateEntryPointScriptUrl,
} from '../../../src/service/extension-location';
import {setStyles} from '../../../src/style';
import {hasOwn} from '../../../src/utils/object';
import {IframeTransportMessageQueue} from './iframe-transport-message-queue';
/** @typedef {{
* frame: Element,
* sentinel: !string,
* usageCount: number,
* queue: IframeTransportMessageQueue,
* }} */
export let FrameData;
/**
* @visibleForTesting
*/
export class IframeTransport {
/**
* @param {!Window} win
* @param {!string} type The value of the amp-analytics tag's type attribute
* @param {!JsonObject} config
*/
constructor(win, type, config) {
/** @private @const {!Window} win */
this.win_ = win;
/** @private @const {string} */
this.type_ = type;
/** @private @const {string} */
this.id_ = IframeTransport.createUniqueId_();
dev().assert(config && config['iframe'],
'Must supply iframe URL to constructor!');
this.frameUrl_ = config['iframe'];
this.processCrossDomainIframe();
}
/**
* Called when a Transport instance is being removed from the DOM
*/
detach() {
IframeTransport.markCrossDomainIframeAsDone(this.win_.document, this.type_);
}
/**
* If iframe is specified in config/transport, check whether third-party
* iframe already exists, and if not, create it.
*/
processCrossDomainIframe() {
let frameData;
if (IframeTransport.hasCrossDomainIframe(this.type_)) {
frameData = IframeTransport.getFrameData(this.type_);
++(frameData.usageCount);
} else {
frameData = this.createCrossDomainIframe();
this.win_.document.body.appendChild(frameData.frame);
}
dev().assert(frameData, 'Trying to use non-existent frame');
}
/**
* Create a cross-domain iframe for third-party vendor anaytlics
* @return {!FrameData}
* @VisibleForTesting
*/
createCrossDomainIframe() {
// Explanation of IDs:
// Each instance of IframeTransport (owned by a specific amp-analytics
// tag, in turn owned by a specific creative) has an ID in this._id.
// Each cross-domain iframe also has an ID, stored here in sentinel.
// These two types of IDs are drawn from the same pool of numbers, and
// are thus mutually unique.
// There is a many-to-one relationship, in that several creatives may
// utilize the same analytics vendor, so perhaps creatives #1 & #2 might
// both use xframe #3.
// Of course, a given creative may use multiple analytics vendors, but
// in that case it would use multiple amp-analytics tags, so the
// iframeTransport.id_ -> sentinel relationship is *not* many-to-many.
const sentinel = IframeTransport.createUniqueId_();
const useLocal = getMode().localDev || getMode().test;
const useRtvVersion = !useLocal;
const scriptSrc = calculateEntryPointScriptUrl(
this.win_.parent.location, 'iframe-transport-client-lib',
useLocal, useRtvVersion);
const frameName = JSON.stringify(/** @type {JsonObject} */ ({
scriptSrc,
sentinel,
}));
const frame = createElementWithAttributes(this.win_.document, 'iframe',
/** @type {!JsonObject} */ ({
sandbox: 'allow-scripts allow-same-origin',
name: frameName,
'data-amp-3p-sentinel': sentinel,
}));
frame.sentinel = sentinel;
setStyles(frame, {
display: 'none',
});
frame.src = this.frameUrl_;
const frameData = /** @const {FrameData} */ ({
frame,
usageCount: 1,
queue: new IframeTransportMessageQueue(this.win_,
/** @type {!HTMLIFrameElement} */
(frame)),
});
IframeTransport.crossDomainIframes_[this.type_] = frameData;
return frameData;
}
/**
* Called when a creative no longer needs its cross-domain iframe (for
* instance, because the creative has been removed from the DOM).
* Once all creatives using a frame are done with it, the frame can be
* destroyed.
* @param {!HTMLDocument} ampDoc The AMP document
* @param {!string} type The type attribute of the amp-analytics tag
*/
static markCrossDomainIframeAsDone(ampDoc, type) {
const frameData = IframeTransport.getFrameData(type);
dev().assert(frameData && frameData.frame && frameData.usageCount,
'Marked the ' + type + ' frame as done, but there is no' +
' record of it existing.');
if (--(frameData.usageCount)) {
// Some other instance is still using it
return;
}
ampDoc.body.removeChild(frameData.frame);
delete IframeTransport.crossDomainIframes_[type];
}
/**
* Returns whether this type of cross-domain frame is already known
* @param {!string} type The type attribute of the amp-analytics tag
* @return {!boolean}
* @VisibleForTesting
*/
static hasCrossDomainIframe(type) {
return hasOwn(IframeTransport.crossDomainIframes_, type);
}
/**
* Create a unique value to differentiate messages from a particular
* creative to the cross-domain iframe, or to identify the iframe itself.
* @returns {string}
* @private
*/
static createUniqueId_() {
return String(++(IframeTransport.nextId_));
}
/**
* Sends an AMP Analytics trigger event to a vendor's cross-domain iframe,
* or queues the message if the frame is not yet ready to receive messages.
* @param {!string} event A string describing the trigger event
* @VisibleForTesting
*/
sendRequest(event) {
const frameData = IframeTransport.getFrameData(this.type_);
dev().assert(frameData, 'Trying to send message to non-existent frame');
dev().assert(frameData.queue, 'Event queue is missing for ' + this.id_);
frameData.queue.enqueue(
/**
* @type {!../../../src/3p-frame-messaging.IframeTransportEvent}
*/
({transportId: this.id_, message: event}));
}
/**
* Gets the FrameData associated with a particular cross-domain frame type.
* @param {!string} type The type attribute of the amp-analytics tag
* @returns {FrameData}
* @VisibleForTesting
*/
static getFrameData(type) {
return IframeTransport.crossDomainIframes_[type];
}
/**
* Removes all knowledge of cross-domain iframes.
* Does not actually remove them from the DOM.
* @VisibleForTesting
*/
static resetCrossDomainIframes() {
IframeTransport.crossDomainIframes_ = {};
}
/**
* @returns {!string} Unique ID of this instance of IframeTransport
* @VisibleForTesting
*/
getId() {
return this.id_;
}
/**
* @returns {!string} Type attribute of parent amp-analytics instance
* @VisibleForTesting
*/
getType() {
return this.type_;
}
}
/** @private {Object<string,FrameData>} */
IframeTransport.crossDomainIframes_ = {};
/** @private {number} */
IframeTransport.nextId_ = 0;