From an iframe, is there a way to trigger a function when a fetch made by the parent is completed?
The issue in detail:
On a website, I'm running an external script in Google Tag Manager (which I don't control) that fetches a set of tracking tags. The script places the tags in hidden fields on a form on the parent page by default. However I want them carried over to hidden fields on an iframed Hubspot form on that page. And I don't want to block the form itself from loading.
I've added placeholder hidden fields on the parent page to catch the fetched values. On the Hubspot forms.create method, I've set the onFormReady listener to run a function to get the values from the placeholder fields, and place them in the hubspot form fields.
This doesn't always work, since onFormReady may fire before the values are fetched and added to the placeholder fields. So the function put empty string into the framed form fields.
Overwriting the fetch request from within the onFormReady listener didn't work. I came across this answer, suggesting using a performance observer, which did work for me. My form embed code now looks like below.
As mentiond, it works, but feels like it abuses the performance observer for something it wasn't meant for, and therefor isn't very robust? I'm curious if there is a better solution for this.
<script>
hbspt.forms.create({
//some Hubspot form properties here
onFormReady: function(form) {
if (!document.querySelector('input[name="UtmSource"]').value) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.initiatorType === 'fetch' && entry.name.includes('https://whatever.com')) {
addTagsToForm();
}
}
});
observer.observe({
entryTypes: ['resource']
});
} else {
addTagsToForm();
};
function addTagsToForm() {
// function to grab values from placeholder fields on parent and add to iframed fields here
}
}
}
});
</script>