Hi there,
We have a Marketo form embedded on our demo page that has some additional customized code in it. We've been running into an issue where cookie values are only being captured ~60% of the time and believe our code might be the culprit here.
Would love a second opinion here and hear if anyone else has encountered this issue before.
Here's the page and form in question and below is the script that sets one of the cookie values through Google Tag Manager, with the trigger to fire on all pages on DOM.
Thanks!
Jake
<script type="text/javascript">
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function setCookie(name, value, days){
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + ";path=/;domain=carta.com";
}
if (getCookie('FirstReferrer') == null) {
setCookie("FirstReferrer","{{Referrer}}","540");
}
</script>
Solved! Go to Solution.
You have a race condition.
This script is loaded asynchronously using GTM (all script-loaded scripts are async). Therefore, there's no guarantee that it will complete before the form reads the cookie store.
You have to either use GTM tag sequencing to ensure load order, or use the Forms JS API to add the hidden fields to the form (which still requires that forms2.min.js be loaded before your custom form behaviors code, since you'll need the global object MktoForms2 to exist to call MktoForms2.addHiddenFields).
Also, I'd recommend a more established cookie parsing library. Not worth reinventing the wheel here (parsing twice for ";" and "; " with a space is far from efficient!).
Please edit your post and use the Advanced Editor's syntax highlighter to highlight your code as JavaScript to continue.
Just edited, thanks for flagging, Sanford.
You have a race condition.
This script is loaded asynchronously using GTM (all script-loaded scripts are async). Therefore, there's no guarantee that it will complete before the form reads the cookie store.
You have to either use GTM tag sequencing to ensure load order, or use the Forms JS API to add the hidden fields to the form (which still requires that forms2.min.js be loaded before your custom form behaviors code, since you'll need the global object MktoForms2 to exist to call MktoForms2.addHiddenFields).
Also, I'd recommend a more established cookie parsing library. Not worth reinventing the wheel here (parsing twice for ";" and "; " with a space is far from efficient!).