MCPcopy
hub / github.com/ampproject/amphtml / createIframeWithMessageStub

Function createIframeWithMessageStub

testing/iframe.js:371–423  ·  view source on GitHub ↗
(win)

Source from the content-addressed store, hash-verified

369 * @return {!HTMLIFrameElement}
370 */
371export function createIframeWithMessageStub(win) {
372 const element = win.document.createElement('iframe');
373 element.src = IFRAME_STUB_URL;
374
375 /**
376 * Instructs the iframe to send a message to parent window.
377 * @param {!Object} msg
378 */
379 element.postMessageToParent = (msg) => {
380 element.src = IFRAME_STUB_URL + encodeURIComponent(JSON.stringify(msg));
381 };
382
383 /**
384 * Returns a Promise that resolves when the iframe acknowledged the reception
385 * of the specified message.
386 * @param {function(?Object, !Object|string)|string} callbackOrType
387 * A callback that determines if this is the message we expected. If a
388 * string is passed, the determination is based on whether the message's
389 * type matches the string.
390 */
391 element.expectMessageFromParent = (callbackOrType) => {
392 let filter;
393 if (typeof callbackOrType === 'string') {
394 filter = (data) => {
395 return 'type' in data && data.type == callbackOrType;
396 };
397 } else {
398 filter = callbackOrType;
399 }
400
401 return new Promise((resolve, reject) => {
402 function listener(event) {
403 if (event.source != element.contentWindow || !event.data.testStubEcho) {
404 return;
405 }
406 const message = event.data.receivedMessage;
407 const data = parseIfNeeded(message);
408 try {
409 if (filter(data, message)) {
410 win.removeEventListener('message', listener);
411 resolve(data || message);
412 }
413 } catch (e) {
414 win.removeEventListener('message', listener);
415 reject(e);
416 }
417 }
418 win.addEventListener('message', listener);
419 });
420 };
421
422 return element;
423}
424
425/**
426 * Returns a Promise that resolves when a post message is observed from the

Calls 2

stringifyMethod · 0.80
addEventListenerMethod · 0.45

Tested by

no test coverage detected