Capture lead before the form/page reloads using Mutation Observer

gerard_reyes Posted by: Gerard Reyes Date Posted: April 25, 2024
Back to Case Studies

Issue

For some reason, when submitting the form, the page reloads before our script can even fire, preventing the capture of the lead.

Solution

I created a Mutation Observer that observes if there is a change in the form instead of waiting for the submit button click. This fires before the page reloads, ensuring the lead is captured.

Code:

 

<script>
if (typeof jQuery != 'undefined') {
     console.log("jQuery is available.");
     jQuery(document).ready(function() {
         var counter = 0;
         setInterval(function() {
         counter = 0;
     }, 2000);

     // Select the target node
     var targetNode = document.getElementById('bbox-root');

     // Create a new instance of MutationObserver
     var observer = new MutationObserver(function(mutationsList) {
     mutationsList.forEach(function(mutation) {
         if (mutation.type === 'attributes' && counter == 0) {
             var $form = $('#mongo-form');
             var $emailInput = $form.find('#bboxdonation_billing_txtEmail');

             // Check if $emailInput exists before accessing its value
             if ($emailInput.length > 0) {
                 var emailValue = $emailInput.val();

                 if (emailValue.trim() !== '') {
                     console.log('MCFX capture success via Observer');
                     mcfx('capture', $form.get(0));
                     counter = 1;
                     return false; // Break out of the forEach loop
                 }
             }
         }
     });
});

     counter = 0;

     // Configuration of the observer:
     var config = {
          attributes: true,
          childList: true,
          subtree: true
     };

     // Start observing the target node for configured mutations
     observer.observe(targetNode, config);
});
} else {
     console.log("jQuery is not available.");
}
</script>

Achievement

The lead was captured.

Snippet/Screenshot/Link

Ticket: Link