SHARE
TWEET

Untitled

a guest Feb 17th, 2017 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2. (function() {
  3.   if (typeof document.querySelectorAll === "undefined") {
  4.     return
  5.   }
  6.     window.addEventListener('beforeunload', function(e) {
  7.       findUnsubmittedForms().forEach(function(it) {
  8.         window.dataLayer.push({
  9.           'event' : 'formAbandonment',
  10.           'eventCategory' : 'Form Abandonment',
  11.           'eventAction' : it.history.join(" > ")
  12.         })
  13.       })
  14.     })
  15.  
  16.     var history = {}
  17.  
  18.     window.addEventListener("load", function() {
  19.       document.addEventListener("change", function(e) {
  20.         var target = e.target
  21.         if (target && target.tagName && (target.tagName.toUpperCase() == "INPUT" || target.tagName.toUpperCase() == "TEXTAREA" || target.tagName.toUpperCase() == "SELECT")) {
  22.           var inputName = target.getAttribute("name")
  23.           var form = target.form
  24.           if (form && inputName) {
  25.             var formName = form.getAttribute("name")
  26.             if (typeof history[formName] == "undefined") {
  27.               history[formName] = []
  28.             }
  29.             if (history[formName].slice(-1) != inputName) {
  30.               history[formName].push(inputName)
  31.             }
  32.           }
  33.         }
  34.       })
  35.     })
  36.  
  37.     function findUnsubmittedForms() {
  38.       return Object.keys(history).filter(hasNoFormSubmitEvent(window.dataLayer)).map(findFormFromHistory).filter(notEmpty)
  39.     }
  40.  
  41.     function hasNoFormSubmitEvent(dataLayer) {
  42.       return function(name) {
  43.         return dataLayer.filter(isFormSubmitEvent).map(getFormName).indexOf(name) == -1
  44.       }
  45.     }
  46.  
  47.     function isFormSubmitEvent(e) {
  48.       return e.event === 'gtm.formSubmit'
  49.     }
  50.  
  51.     function getFormName(e) {
  52.       return e['gtm.element'].name
  53.     }
  54.  
  55.     function findFormFromHistory(name) {
  56.       return {
  57.         name: name,
  58.         history: (history[name] || [])
  59.       }
  60.     }
  61.  
  62.     function notEmpty(form) {
  63.       return form.history.length > 0
  64.     }
  65.  
  66. })()
  67. </script>
RAW Paste Data
Top