Sending Site Data to iFrame on Different Domain

Having an iFrame (i.e. forms hosted via 3rd party tools) that exists on a different domain poses problems for site analytics implementations, as passing data to / from an iFrame does not happen by default. There are several approaches based on which domain is receiving the message. The following example illustrates a parent domain (sender) and a child iFrame (receiver).

 

Implement the following code on the parent domain (sender):

// replace _IFRAME_ with the CSS selector for child iFrame receiver
var cf = document.querySelectorAll("_IFRAME_")[0].contentWindow;
var loc = document.querySelectorAll("_IFRAME_")[0].src;
// replace _MESSAGE_ with the variable to be sent
var message = "_MESSAGE_";
cf.postMessage(message, loc);

NOTE: _MESSAGE_ can be taken from a cookie, session storage, query string parameter, etc.

 

Implement the following code on the child iFrame (receiver):

window.addEventListener("message", function(event) {
    // replace _PARENT_DOMAIN_ the domain of the parent (sender)
    if (event.origin !== "_PARENT_DOMAIN_") {
        return;
    } else {
        try {
            var message = event.data; // data sent from the parent domain
        } catch (err) {
            // fail gracefully
        }
    }
});

NOTE: The variable “message“ can now be leveraged within the iFame as per your requirements.