Mixpanel track_links does not work with dynamically added elements

前端 未结 2 1391
渐次进展
渐次进展 2020-12-15 13:27

I\'m having trouble using mixpanel.track_links with links added dynamically (after page load).

For a general example, given this page:

相关标签:
2条回答
  • 2020-12-15 13:59

    I had a somewhat hard time trying to get tracking links working as expected on react. The main caveat I noticed was that duplicated events may be sent to mixpanel in bursts. I used a slightly modified version of @Kyle to solve my problem. Additionally, this accounts for properties being possibly a function as supported by the mixpanel API.

    // mixpanelSetup.js
    import md5 from "md5";
    
    const setup = () => {
      mixpanel.init(TOKEN);
      // Sets ensure unique items
      mixpanel.delegated_links = new Set();
      mixpanel.delegate_links = (parent, selector, eventName, eventProperties, {ignoreUrl=false}) => {
        // Hash by whatever thing(s) the use case considers 'unique' (e.g md5(`${selector}__${eventName}`))
        const linkHash = md5(selector);
        parent = parent || document.body;
        parent = $(parent);
        // Do not add additional trackers for an already tracked event.
        if (mixpanel.delegated_links.has(linkHash)) {
          return;
        }
        mixpanel.delegated_links.add(linkHash);
        parent.on("click", selector, (event) => {
          const newTab = event.which === 2 || event.metaKey || event.target.target === "_blank";
          if (typeof eventProperties === "function") {
            eventProperties = eventProperties(event.target) || {};
          }
          eventProperties.url = event.target.href;
          // In case we don't want the url on the properties.
          if (ignoreUrl) {
            delete eventProperties.url;
          }
          const callback = () => {
            if (newTab) {
              return;
            }
            window.location = event.target.href;
          };
          if (!newTab) {
            event.preventDefault();
            setTimeout(callback, 300);
          }
          console.debug("Tracking link click!");
          mixpanel.track(eventName, eventProperties, callback);
        });
      };
    }
    

    And can be used as:

    // MyComponent.jsx
    import React, { useEffect } from "react";
    import { Link, useLocation } from "@reach/router";
    
    const MyComponent = ({ moduleName, key, ...props }) => {
      const id = `#${id}__${moduleName}`;
    
      useEffect(() => {
        mixpanel.delegate_links(document.parent, id, event => {
          return {
              module: event.id.split("__").pop(),
              ...props.otherPropsToTrack
          };
        })
      }, [])
    
      return <>
        <Link {...props} to="/some/path" id={id}>My Page</Link>
      </>
    }
    
    0 讨论(0)
  • 2020-12-15 14:10

    I was curious so I checked out their code and went ahead and did as they suggested. I tested it, and it worked fine. This requires jQuery though.

    Example usage: mixpanel.delegate_links(document.body, 'a', 'clicked link');

    // with jQuery and mixpanel
    mixpanel.delegate_links = function (parent, selector, event_name, properties) {
        properties = properties || {};
        parent = parent || document.body;
        parent = $(parent);
    
        parent.on('click', selector, function (event) {
            var new_tab = event.which === 2 || event.metaKey || event.target.target === '_blank';
    
            properties.url = event.target.href;
    
            function callback() {
                if (new_tab) {
                    return;
                }
    
                window.location = properties.url;
            }
    
            if (!new_tab) {
                event.preventDefault();
                setTimeout(callback, 300);
            }
    
            mixpanel.track(event_name, properties, callback);
        });
    };
    
    0 讨论(0)
提交回复
热议问题