Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

feat(modular): support handleLink function (#68418)

Nicolò Pretto6a400ce43aee
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.ts
index 1a52cd2df9e..ec152e665c6 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
@@ -1,3 +1,4 @@
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
ORDERS_COUNT_QUESTION_ID,
ORDERS_DASHBOARD_ENTITY_ID,
@@ -7,6 +8,7 @@ import {
} from "e2e/support/cypress_sample_instance_data";
const { H } = cy;
+const { ORDERS_ID: ORDERS_TABLE_ID, ORDERS } = SAMPLE_DATABASE;
describe("scenarios > embedding > modular embedding", () => {
beforeEach(() => {
@@ -376,6 +378,89 @@ describe("scenarios > embedding > modular embedding", () => {
});
});
+ describe("handleLink", () => {
+ beforeEach(() => {
+ // Create a question with a URL column for testing handleLink
+ cy.signInAsAdmin();
+ H.createDashboardWithQuestions({
+ dashboardName: "Dashboard with links",
+ questions: [
+ {
+ name: "Question with link column",
+ query: {
+ "source-table": ORDERS_TABLE_ID,
+ expressions: {
+ "link url": [
+ "concat",
+ "https://example.org/order/",
+ ["field", ORDERS.ID, { "base-type": "type/BigInteger" }],
+ ],
+ },
+ fields: [
+ ["field", ORDERS.ID, { "base-type": "type/BigInteger" }],
+ ["expression", "link url", { "base-type": "type/Text" }],
+ ],
+ limit: 5,
+ },
+ visualization_settings: {
+ column_settings: {
+ '["name","ID"]': {
+ view_as: "link",
+ link_text: "Order {{ID}}",
+ link_url: "https://example.org/order/{{ID}}",
+ },
+ },
+ },
+ },
+ ],
+ cards: [{ size_x: 24, size_y: 6, col: 0, row: 0 }],
+ }).then(({ dashboard }) => {
+ cy.wrap(dashboard.id).as("linkDashboardId");
+ });
+
+ cy.signOut();
+ });
+
+ it("calls handleLink when a link is clicked and prevents navigation when handled: true", function () {
+ const frame = H.loadSdkIframeEmbedTestPage({
+ elements: [
+ {
+ component: "metabase-dashboard",
+ attributes: {
+ dashboardId: this.linkDashboardId,
+ },
+ },
+ ],
+ insertHtml: {
+ afterEmbed: `
+ <script>
+ window.handleLinkCalls = [];
+ window.metabaseConfig.pluginsConfig = {
+ handleLink: (url) => {
+ window.handleLinkCalls.push(url);
+ return { handled: true };
+ },
+ };
+ </script>
+ `,
+ },
+ });
+
+ cy.wait("@getDashCardQuery");
+
+ frame.within(() => {
+ cy.findByText("Order 448").click();
+ });
+
+ // Verify handleLink was called with the correct URL
+ cy.window()
+ .its("handleLinkCalls")
+ .should("have.length", 1)
+ .its(0)
+ .should("include", "https://example.org/order/448");
+ });
+ });
+
describe("analytics", () => {
beforeEach(() => {
H.resetSnowplow();
diff --git a/frontend/src/embedding-sdk-shared/lib/sdk-global-plugins.ts b/frontend/src/embedding-sdk-shared/lib/sdk-global-plugins.ts
index 8bd0f8da445..967ddd4b680 100644
--- a/frontend/src/embedding-sdk-shared/lib/sdk-global-plugins.ts
+++ b/frontend/src/embedding-sdk-shared/lib/sdk-global-plugins.ts
@@ -1,3 +1,6 @@
+import { bridgeHandleLinkForEmbedJs } from "metabase/embedding/embedding-iframe-sdk/utils/bridge-handle-link";
+import { isEmbeddingEajs } from "metabase/embedding-sdk/config";
+
import { ensureMetabaseProviderPropsStore } from "./ensure-metabase-provider-props-store";
type HandleLinkFn = (url: string) => { handled: boolean };
@@ -18,8 +21,17 @@ export const getSdkGlobalPlugins = (): SdkGlobalPlugins => {
/**
* Invokes the handleLink plugin if configured in the host app and returns an object with a 'handled' property, indicating if the host app handled the link.
+ * For iframe SDK, this sends a postMessage to the parent window and awaits the response.
*/
-export function handleLinkSdkPlugin(url: string): { handled: boolean } {
+export async function handleLinkSdkPlugin(
+ url: string,
+): Promise<{ handled: boolean }> {
+ // In iframe SDK mode, send a message to the parent window
+ if (isEmbeddingEajs()) {
+ return bridgeHandleLinkForEmbedJs(url);
+ }
+
+ // React SDK mode - use the global plugins
const globalPlugins = getSdkGlobalPlugins();
if (!globalPlugins?.handleLink) {
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
index eff9085461e..3f97544c3d4 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
@@ -27,6 +27,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {
"useExistingUserSession",
"isGuest",
"jwtProviderUri",
+ "pluginsConfig",
] satisfies (keyof SdkIframeEmbedBaseSettings)[],
dashboard: [
"dashboardId",
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
index aad5eff23b9..625f8446aa8 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
@@ -433,6 +433,30 @@ export abstract class MetabaseEmbedElement
if (event.data.type === "metabase.embed.requestSessionToken") {
await this._authenticate();
}
+
+ // Note: if we wrap other functions like this, let's come up with a generic utility function
+ if (event.data.type === "metabase.embed.handleLink") {
+ const { url, requestId } = event.data.data;
+ const handleLink = this.globalSettings.pluginsConfig?.handleLink;
+
+ let handled = false;
+ if (typeof handleLink === "function") {
+ try {
+ const result = handleLink(url);
+ handled = result?.handled ?? false;
+ } catch (e) {
+ console.error("[metabase.embed] handleLink error:", e);
+ }
+ }
+
+ this._iframe?.contentWindow?.postMessage(
+ {
+ type: "metabase.embed.handleLinkResponse",
+ data: { requestId, handled },
+ },
+ "*",
+ );
+ }
};
sendMessage<Message extends SdkIframeEmbedMessage>(
@@ -443,7 +467,8 @@ export abstract class MetabaseEmbedElement
const normalizedData = Object.entries(data).reduce(
(acc, [key, value]) => {
// Functions are not serializable, so we ignore them.
- if (typeof value === "function") {
+ // `pluginsConfig` contains functions so we also skip it.
+ if (typeof value === "function" || key === "pluginsConfig") {
return acc;
}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
index ea9146e08d2..b03ec51a702 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
@@ -25,7 +25,8 @@ import type { ModularEmbeddingEntityType } from "metabase-types/store/embedding-
/** Events that the embed.js script listens for */
export type SdkIframeEmbedTagMessage =
| SdkIframeEmbedTagIframeReadyMessage
- | SdkIframeEmbedTagRequestSessionTokenMessage;
+ | SdkIframeEmbedTagRequestSessionTokenMessage
+ | SdkIframeEmbedTagHandleLinkMessage;
export type SdkIframeEmbedTagIframeReadyMessage = {
type: "metabase.embed.iframeReady";
@@ -33,13 +34,18 @@ export type SdkIframeEmbedTagIframeReadyMessage = {
export type SdkIframeEmbedTagRequestSessionTokenMessage = {
type: "metabase.embed.requestSessionToken";
};
+export type SdkIframeEmbedTagHandleLinkMessage = {
+ type: "metabase.embed.handleLink";
+ data: { url: string; requestId: string };
+};
/** Events that the sdk embed route listens for */
export type SdkIframeEmbedMessage =
| SdkIframeEmbedSetSettingsMessage
| SdkIframeEmbedSubmitSessionTokenMessage
| SdkIframeEmbedReportAuthenticationError
- | SdkIframeEmbedReportAnalytics;
+ | SdkIframeEmbedReportAnalytics
+ | SdkIframeEmbedHandleLinkResponse;
export type SdkIframeEmbedSetSettingsMessage = {
type: "metabase.embed.setSettings";
@@ -65,6 +71,10 @@ export type SdkIframeEmbedReportAnalytics = {
embedHostUrl: string;
};
};
+export type SdkIframeEmbedHandleLinkResponse = {
+ type: "metabase.embed.handleLinkResponse";
+ data: { requestId: string; handled: boolean };
+};
// --- Embed Option Interfaces ---
@@ -201,6 +211,11 @@ export type SdkIframeEmbedBaseSettings = {
// Whether the embed is running on localhost. Cannot be set by the user.
_isLocalhost?: boolean;
+
+ pluginsConfig?: {
+ // Callback to handle link clicks. Return { handled: true } to prevent default navigation.
+ handleLink?: (url: string) => { handled: boolean };
+ };
};
export type SdkIframeEmbedAuthTypeSettings = {
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/bridge-handle-link.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/bridge-handle-link.ts
new file mode 100644
index 00000000000..904126270ce
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/bridge-handle-link.ts
@@ -0,0 +1,41 @@
+import type {
+ SdkIframeEmbedMessage,
+ SdkIframeEmbedTagMessage,
+} from "../types/embed";
+
+/**
+ * Requests the parent window (embed.js) to handle a link click.
+ * Returns { handled: true } if the parent handled the link, { handled: false } otherwise.
+ */
+export function bridgeHandleLinkForEmbedJs(
+ url: string,
+): Promise<{ handled: boolean }> {
+ return new Promise((resolve) => {
+ const requestId = crypto.randomUUID();
+
+ const handler = (event: MessageEvent<SdkIframeEmbedMessage>) => {
+ if (!event.data) {
+ return;
+ }
+
+ const action = event.data;
+
+ if (
+ action.type === "metabase.embed.handleLinkResponse" &&
+ action.data.requestId === requestId
+ ) {
+ window.removeEventListener("message", handler);
+ resolve({ handled: action.data.handled });
+ }
+ };
+
+ window.addEventListener("message", handler);
+
+ const handleLinkMessage: SdkIframeEmbedTagMessage = {
+ type: "metabase.embed.handleLink",
+ data: { url, requestId },
+ };
+
+ window.parent.postMessage(handleLinkMessage, "*");
+ });
+}
diff --git a/frontend/src/metabase/lib/dom.js b/frontend/src/metabase/lib/dom.js
index 8cfe836c133..202fedbd14d 100644
--- a/frontend/src/metabase/lib/dom.js
+++ b/frontend/src/metabase/lib/dom.js
@@ -297,7 +297,7 @@ window.addEventListener(
* helper for opening links in same or different window depending on origin and
* meta key state
*/
-export function open(
+export async function open(
url,
{
// custom function for opening in same window
@@ -312,10 +312,13 @@ export function open(
) {
url = ignoreSiteUrl ? url : getWithSiteUrl(url);
- // In the react sdk, allow the host app to override how to open links
- if (isEmbeddingSdk() && handleLinkSdkPlugin(url).handled) {
- // Plugin handled the link, don't continue with default behavior
- return;
+ // In the sdk, allow the host app to override how to open links
+ if (isEmbeddingSdk()) {
+ const result = await handleLinkSdkPlugin(url);
+ if (result.handled) {
+ // Plugin handled the link, don't continue with default behavior
+ return;
+ }
}
if (shouldOpenInBlankWindow(url, options)) {
diff --git a/frontend/src/metabase/lib/formatting/url.tsx b/frontend/src/metabase/lib/formatting/url.tsx
index e555c031044..b0385c58ea6 100644
--- a/frontend/src/metabase/lib/formatting/url.tsx
+++ b/frontend/src/metabase/lib/formatting/url.tsx
@@ -55,9 +55,12 @@ export function formatUrl(value: string, options: OptionsType = {}) {
const onClickCaptureInSdk = isEmbeddingSdk()
? {
- onClickCapture: (e: React.MouseEvent<HTMLAnchorElement>) => {
- if (handleLinkSdkPlugin(url).handled) {
- e.preventDefault();
+ onClickCapture: async (e: React.MouseEvent<HTMLAnchorElement>) => {
+ e.preventDefault(); // Prevent immediately while we await the response
+ const result = await handleLinkSdkPlugin(url);
+ if (!result.handled) {
+ // Parent didn't handle it - proceed with default navigation
+ window.open(url, "_blank", "noopener");
}
},
}
diff --git a/frontend/test/metabase/lib/dom.unit.spec.js b/frontend/test/metabase/lib/dom.unit.spec.js
index 96bec68668d..26e5e162785 100644
--- a/frontend/test/metabase/lib/dom.unit.spec.js
+++ b/frontend/test/metabase/lib/dom.unit.spec.js
@@ -110,7 +110,7 @@ describe("open()", () => {
ensureMetabaseProviderPropsStore().cleanup();
});
- it("should prevent default behavior when handleLink returns { handled: true }", () => {
+ it("should prevent default behavior when handleLink returns { handled: true }", async () => {
const handleLink = jest.fn().mockReturnValue({ handled: true });
ensureMetabaseProviderPropsStore().setProps({
pluginsConfig: { handleLink },
@@ -120,7 +120,7 @@ describe("open()", () => {
const openInBlankWindow = jest.fn();
const url = "https://example.com/dashboard/1";
- open(url, {
+ await open(url, {
openInSameWindow,
openInBlankWindow,
});
@@ -130,7 +130,7 @@ describe("open()", () => {
expect(openInBlankWindow).not.toHaveBeenCalled();
});
- it("should allow default behavior when handleLink returns { handled: false }", () => {
+ it("should allow default behavior when handleLink returns { handled: false }", async () => {
const handleLink = jest.fn().mockReturnValue({ handled: false });
ensureMetabaseProviderPropsStore().setProps({
pluginsConfig: { handleLink },
@@ -140,7 +140,7 @@ describe("open()", () => {
const openInBlankWindow = jest.fn();
const url = "https://example.com/dashboard/1";
- open(url, {
+ await open(url, {
openInSameWindow,
openInBlankWindow,
});
@@ -149,7 +149,7 @@ describe("open()", () => {
expect(openInBlankWindow).toHaveBeenCalledWith(url);
});
- it("should throw error when handleLink returns invalid value", () => {
+ it("should throw error when handleLink returns invalid value", async () => {
const handleLink = jest.fn().mockReturnValue(true);
ensureMetabaseProviderPropsStore().setProps({
pluginsConfig: { handleLink },
@@ -159,12 +159,12 @@ describe("open()", () => {
const openInBlankWindow = jest.fn();
const url = "https://example.com/dashboard/1";
- expect(() =>
+ await expect(
open(url, {
openInSameWindow,
openInBlankWindow,
}),
- ).toThrow(
+ ).rejects.toThrow(
"handleLink plugin must return an object with a 'handled' property",
);
@@ -182,7 +182,7 @@ describe("open()", () => {
const openInBlankWindow = jest.fn();
const url = "https://example.com/dashboard/1";
- open(url, {
+ await open(url, {
openInSameWindow,
openInBlankWindow,
});