/** * @url https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage * This is a script that a user puts inside of the iframe. This script communicates to the parent window * using postMessage API. The script loops through a given list of elements of a form, * constructs a payload with a signature of { name: value } and sends it to the parent that's * listening for messages on a "dreamdata-message" "channel". * * This script is not built as a module, as it requires no dependencies. * Due to this script, "isolatedModules" inside of tsconfig.json is set to false */ import { logger } from '../../../logger' import { NameValuePair } from '../../types' const IFRAME_SCRIPT_ID = 'dreamdata-iframe' function handleLoad() { const currentScript = document.getElementById( IFRAME_SCRIPT_ID ) as HTMLScriptElement if (!currentScript) { logger.error('The script tag could not be found.') return } const formName = currentScript.getAttribute('form-name') || 'form-iframe-submit' document.querySelectorAll('form').forEach((form: HTMLFormElement) => { if (!Object.keys(form.elements).length) { logger.debugError('The form has no input fields. Skipping...') return } form.addEventListener('submit', () => { const elements: HTMLFormControlsCollection = form.elements const fields: NameValuePair[] = Array.from(elements).map((input) => { const { name, value } = input as HTMLInputElement return { name, value, } }) logger.debug(`IframeChild: Found fields ${JSON.stringify(fields)}`) const messageData = { fields, formName, type: 'dreamdata-message', } logger.debug( `IframeChild: Form with the name "${formName}" was submitted` ) parent.postMessage(messageData, '*') }) }) } window.addEventListener('load', () => { try { handleLoad() } catch (error) { console.error(error) } })