The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
fix(embed-js): Only report analytics when not in the preview (#63812)
Mahatthana (Kelvin) Nomsawadibbccbb484239
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.tsindex 59945b8cf04..972df614e4b 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts@@ -315,13 +315,18 @@ H.describeWithSnowplowEE(() => {beforeEach(() => {H.resetSnowplow();- H.prepareSdkIframeEmbedTest({ signOut: false });+ H.prepareSdkIframeEmbedTest({+ enabledAuthMethods: ["jwt"],+ signOut: false,+ });H.enableTracking();- cy.signOut();});it("should send an Embedded Analytics JS usage event", () => {+ cy.signOut();+ cy.visit("http://localhost:4000");const frame = H.loadSdkIframeEmbedTestPage({+ origin: "http://different-than-metabase-instance.com",elements: [{component: "metabase-dashboard",@@ -405,6 +410,26 @@ H.describeWithSnowplowEE(},});});++ it("should not send an Embedded Analytics JS usage event in the preview", () => {+ cy.visit("/embed-js");++ H.waitForSimpleEmbedIframesToLoad();+ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByText("Orders in a dashboard").should("be.visible");+ });++ H.expectUnstructuredSnowplowEvent(+ {+ event: "setup",+ global: {+ auth_method: "session",+ },+ },+ // Expect that the usage event shouldn't be sent+ 0,+ );+ });},);diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.tsindex c5fb8d78705..e4dec6ba4b9 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.ts@@ -58,10 +58,12 @@ function reportAnalyticsOnce(activeEmbeds: Set<MetabaseEmbedElement>) {if (!isAnalyticsReported) {isAnalyticsReported = true;const [firstEmbed] = activeEmbeds;- firstEmbed.sendMessage(- "metabase.embed.reportAnalytics",- createEmbeddedAnalyticsJsUsage(activeEmbeds),- );+ firstEmbed.addEventListener("ready", () => {+ firstEmbed.sendMessage("metabase.embed.reportAnalytics", {+ usageAnalytics: createEmbeddedAnalyticsJsUsage(activeEmbeds),+ embedHostUrl: window.location.href,+ });+ });}}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsxindex 7644115667b..c8e0071f78a 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx@@ -40,7 +40,9 @@ const store = getSdkStore();createTracker(store);export const SdkIframeEmbedRoute = () => {- const { embedSettings } = useSdkIframeEmbedEventBus({ onSettingsChanged });+ const { embedSettings } = useSdkIframeEmbedEventBus({+ onSettingsChanged,+ });// The embed settings won't be available until the parent sends it via postMessage.// The SDK will show its own loading indicator, so we don't need to show it twice.diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.tsindex b66233c8509..d243ddb6984 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.ts@@ -3,6 +3,7 @@ import { match } from "ts-pattern";import { trackSchemaEvent } from "metabase/lib/analytics";import { isWithinIframe } from "metabase/lib/dom";+import type { EmbeddedAnalyticsJsEventSchema } from "metabase-types/analytics/embedded-analytics-js";import type {SdkIframeEmbedMessage,@@ -11,6 +12,11 @@ import type {type Handler = (event: MessageEvent<SdkIframeEmbedMessage>) => void;+type UsageAnalytics = {+ usage: EmbeddedAnalyticsJsEventSchema;+ embedHostUrl: string;+};+export function useSdkIframeEmbedEventBus({onSettingsChanged,}: {@@ -20,6 +26,9 @@ export function useSdkIframeEmbedEventBus({} {const [embedSettings, setEmbedSettings] =useState<SdkIframeEmbedSettings | null>(null);+ const [usageAnalytics, setUsageAnalytics] = useState<UsageAnalytics | null>(+ null,+ );useEffect(() => {const messageHandler: Handler = (event) => {@@ -33,7 +42,10 @@ export function useSdkIframeEmbedEventBus({onSettingsChanged?.(data);}).with({ type: "metabase.embed.reportAnalytics" }, ({ data }) => {- trackSchemaEvent("embedded_analytics_js", data);+ setUsageAnalytics({+ usage: data.usageAnalytics,+ embedHostUrl: data.embedHostUrl,+ });});};@@ -47,5 +59,34 @@ export function useSdkIframeEmbedEventBus({};}, [onSettingsChanged]);+ useEffect(() => {+ if (embedSettings?.instanceUrl && usageAnalytics) {+ const isEmbeddedAnalyticsJsPreview = isMetabaseInstance(+ embedSettings.instanceUrl,+ usageAnalytics.embedHostUrl,+ );+ if (!isEmbeddedAnalyticsJsPreview) {+ trackSchemaEvent("embedded_analytics_js", usageAnalytics.usage);+ }+ }+ }, [embedSettings?.instanceUrl, usageAnalytics]);+return { embedSettings };}++export function isMetabaseInstance(instanceUrl: string, embedHostUrl: string) {+ const instanceUrlObject = new URL(instanceUrl);+ const embedHostObject = new URL(embedHostUrl);++ const normalizedInstanceUrl =+ instanceUrlObject.host + instanceUrlObject.pathname;+ const normalizedEmbedHostUrl =+ embedHostObject.host + embedHostObject.pathname;++ /**+ * This is to ensure Metabase at Subpath works. e.g. https://example.com/metabase and https://example.com/embed+ * should be considered as a separate host. But https://example.com/metabase and https://example.com/metabase/dashboard/1+ * are the same host.+ */+ return normalizedEmbedHostUrl.startsWith(normalizedInstanceUrl);+}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.unit.spec.tsnew file mode 100644index 00000000000..41727f4ad49--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.unit.spec.ts@@ -0,0 +1,52 @@+import { isMetabaseInstance } from "./use-sdk-iframe-embed-event-bus";++describe("use-sdk-iframe-embed-event-bus", () => {+ describe("isMetabaseInstance", () => {+ it("returns true for same host with different protocols", () => {+ expect(+ isMetabaseInstance(+ "https://example.com/metabase",+ "http://example.com/metabase/other-path",+ ),+ ).toBe(true);+ });++ it("returns false for different hosts", () => {+ expect(+ isMetabaseInstance(+ "https://example.com",+ "https://another-example.com/path",+ ),+ ).toBe(false);+ });++ it("returns false for subdomains", () => {+ expect(+ isMetabaseInstance(+ "https://sub.example.com/path",+ "https://example.com/path",+ ),+ ).toBe(false);+ });++ describe("Metabase at subpath", () => {+ it("returns true for same host with same subpaths", () => {+ expect(+ isMetabaseInstance(+ "https://example.com/metabase",+ "https://example.com/metabase/other-path",+ ),+ ).toBe(true);+ });++ it("returns false for same host with different subpaths", () => {+ expect(+ isMetabaseInstance(+ "https://example.com/metabase",+ "https://example.com/other-path",+ ),+ ).toBe(false);+ });+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.tsindex 7452aa18726..4df1593067b 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts@@ -39,7 +39,10 @@ export type SdkIframeEmbedMessage =}| {type: "metabase.embed.reportAnalytics";- data: EmbeddedAnalyticsJsEventSchema;+ data: {+ usageAnalytics: EmbeddedAnalyticsJsEventSchema;+ embedHostUrl: string;+ };};// --- Embed Option Interfaces ---