segmentio / analytics-next

Segment Analytics.js 2.0
https://segment.com/docs/connections/sources/catalog/libraries/website/javascript
MIT License
403 stars 136 forks source link

How to use `globalAnalyticsKey` in the browser, using Vanilla JS? #1014

Closed seg-leonelsanches closed 8 months ago

seg-leonelsanches commented 9 months ago

Hi team,

A customer doesn't want to use window.analytics due to a clash with another analytics.js library that it is not ours. They'd like to rename the global object to something like window.segment_analytics.

I found in the docs a property for it:

/**
 * Stores the global window analytics key
 */
let _globalAnalyticsKey = 'analytics'

However, there are no examples on how to use it, so using a little bit of debugging + reading the original code, I crafted this PoC:

<html>
  <head>
    <script>
      !(function () {
        var segment_analytics = (window.segment_analytics = window.segment_analytics || []);
        if (!segment_analytics.initialize)
          if (segment_analytics.invoked)
            window.console &&
              console.error &&
              console.error("Segment snippet included twice.");
          else {
            segment_analytics.invoked = !0;
            segment_analytics.methods = [
              "trackSubmit",
              "trackClick",
              "trackLink",
              "trackForm",
              "pageview",
              "identify",
              "reset",
              "group",
              "track",
              "ready",
              "alias",
              "debug",
              "page",
              "once",
              "off",
              "on",
              "addSourceMiddleware",
              "addIntegrationMiddleware",
              "setAnonymousId",
              "addDestinationMiddleware",
            ];
            segment_analytics.factory = function (e) {
              return function () {
                var t = Array.prototype.slice.call(arguments);
                t.unshift(e);
                segment_analytics.push(t);
                return segment_analytics;
              };
            };
            for (var e = 0; e < segment_analytics.methods.length; e++) {
              var key = segment_analytics.methods[e];
              segment_analytics[key] = segment_analytics.factory(key);
            }
            segment_analytics.load = function (key, e) {
              var t = document.createElement("script");
              t.type = "text/javascript";
              t.async = !0;
              t.src = "https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";
              var n = document.getElementsByTagName("script")[0];
              n.parentNode.insertBefore(t, n);
              segment_analytics._loadOptions = {...e, globalAnalyticsKey: 'segment_analytics' };
            };
            segment_analytics._writeKey = "my-write-key";
            segment_analytics.SNIPPET_VERSION = "4.15.3";
            segment_analytics.load("my-write-key");
          }
      })();
    </script>
    <title>Home</title>
  </head>
  <body>
    <h1>PoC for Global Analytics Key</h1>
  </body>
</html>

This runs with no errors. However, when I send events using it, 1) the events are not sent to Segment, and 2) curiously, the events are added to segment_analytics as an array:

image

Am I setting this correctly? Is there another way of setting it?

Thanks in advance!