Last active
November 7, 2023 12:34
-
-
Save webhasan/e441313da3a1f5d889506202c681d0c2 to your computer and use it in GitHub Desktop.
iFrame From Tracking With GTM by Post Message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// iframe code | |
(function() { | |
var form = document.querySelector('form[action="FormConfirmation.aspx?sourceformid=41&formid=42"]'); | |
if(form) { | |
var queryString = form.getAttribute('action'); | |
form.addEventListener('submit', function (event) { | |
var formData = new FormData(this); | |
var userInputs = {}; | |
formData.forEach(function(value, key) { | |
userInputs[key] = value; | |
}); | |
window.top.postMessage(JSON.stringify(userInputs), 'https://www.main-website.com'); | |
}); | |
} | |
})(); | |
//website code | |
window.addEventListener('message', function (event) { | |
if(event.origin !== 'https://iframe-site.com') return false; | |
var data = JSON.parse(event.data); | |
window.dataLayer = window.dataLayer || []; | |
dataLayer.push({ | |
event: 'iframe_form_submit', | |
formData: data | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment