theme-scripts icon indicating copy to clipboard operation
theme-scripts copied to clipboard

Facebook pixel firing twice on theme-cart actions

Open dan-gamble opened this issue 6 years ago • 0 comments

We've recently found on a merchant of ours an issue were the Facebook pixel was firing twice. This was just a regular pixel install by supplying the id in the admin. No custom code.

What I noticed in the shops_events_listeners.js was the parts below:

function o(e) {
  if (!((e = e || window.event).defaultPrevented || e.isDefaultPrevented && e.isDefaultPrevented())) {
    var t = e.target || e.srcElement;
    if (t && (t.getAttribute("action") || t.getAttribute("href")))
      try {
        var n = c((t.id.options ? t.id.options[t.id.selectedIndex] : t.id).value);
        n.quantity = (t.quantity ? t.quantity.value : 1).to_s,
          window.ShopifyAnalytics.lib.track("Added Product", n),
          window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_track_added_product/1.0", n)
      } catch (r) {
        console && console.warn && console.warn("[shop_events_listener] Error in handleSubmitCartAdd: " + r.message)
      }
  }
}
'function' == typeof t && (e.fetch = function () {
  var n = arguments
  return t.apply(this, Array.prototype.slice.call(arguments)).then(function (e) {
    if (!e.ok)
      return e
    try {
      switch (!0) {
        case e.url.includes('/cart/add.js'):
          o(e, i(n[1].body))
          break
        case e.url.includes('/cart/change.js'):
        case e.url.includes('/cart/clear.js'):
        case e.url.includes('/cart.js'):
          r(e)
      }
    } catch (t) {
      a(t)
    }
    return e
  })
})

These are both callbacks for event listeners added by Shopify.

The 2nd will trigger when any of the 4 URLs are called (/cart/{add,change,clear}.js, /cart.js). theme-cart.js naturally uses these.

The 1st get's triggered when a form is submitted that has an action or a href. Naturally, when doing our forms we had them so if Javascript wasn't enabled then we kept the action so they would submit.

We found we could game the 1st event by removing the action so it wouldn't fire.

Is there a better way to manage this?

dan-gamble avatar Jan 21 '20 16:01 dan-gamble