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
Closes EMB-982 embedding stuck on 404 when navigating with postMessage (#65662)
Sébastiena033c120897f
diff --git a/e2e/support/helpers/e2e-embedding-iframe-interactive-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-interactive-helpers.tsnew file mode 100644index 00000000000..7adfad58d1d--- /dev/null+++ b/e2e/support/helpers/e2e-embedding-iframe-interactive-helpers.ts@@ -0,0 +1,105 @@+import { getIframeBody } from "./e2e-embedding-helpers";++/**+ * Base interface for interactive embedding test page options+ */+interface BaseEmbedTestPageOptions {+ dashboardId: number | string;+ iframeSelector?: string;+}++/**+ * Creates and loads a test fixture for interactive iframe embedding tests+ */+export function loadInteractiveIframeEmbedTestPage({+ iframeSelector,+ ...options+}: BaseEmbedTestPageOptions) {+ const testPageSource = getInteractiveHtml(options);++ const testPageUrl = `${origin}/interactive-iframe-test-page`;++ cy.intercept("GET", testPageUrl, {+ body: testPageSource,+ headers: { "content-type": "text/html" },+ }).as("dynamicPage");++ cy.visit(testPageUrl);+ cy.title().should("include", "Metabase Embed Test");++ return getIframeBody(iframeSelector);+}++interface PostMessageOptions {+ /**+ * CSS selector for the iframe to post the message to+ * @example `iframe[src*="localhost:4000/dashboard"]`+ */+ iframeSelector: string;++ /**+ * Something like `{ metabase: { type: "location", location: "/dashboard/9999990" } }` for instance+ */+ messageData: any;+}++export function postMessageToIframe(options: PostMessageOptions) {+ const { messageData, iframeSelector } = options;++ // this madness is necessary to simulate a real MessageEvent coming from the parent window+ // because in frontend/src/metabase/lib/embed.js we check e.source === window.parent+ cy.get(iframeSelector)+ .should("be.visible")+ .then(($iframe) => {+ const iframeEl = $iframe[0] as HTMLIFrameElement;+ // Get the actual parent window from the iframe's perspective+ const actualParent = iframeEl.ownerDocument.defaultView;+ const targetWin = iframeEl.contentWindow;++ if (!actualParent || !targetWin) {+ throw new Error("Could not access iframe or its parent window");+ }++ // Create a MessageEvent manually with the correct source+ const event = new MessageEvent("message", {+ data: messageData,+ origin: actualParent.location.origin,+ source: actualParent,+ });++ targetWin.dispatchEvent(event);+ });++ return getIframeBody(iframeSelector);+}++/**+ * Base HTML template for embedding test pages+ */+function getInteractiveHtml({ dashboardId }: BaseEmbedTestPageOptions) {+ const MB_BASE_URL = "http://localhost:4000";++ const url = `${MB_BASE_URL}/dashboard/${dashboardId}`;++ return `+ <!DOCTYPE html>+ <html>+ <head>+ <title>Metabase Embed Test</title>++ <style>+ body {+ margin: 0;+ }+ </style>+ </head>+ <body>+ <iframe+ src="${url}"+ style="position: absolute; height: 100%; width:99%; border: none; border: 2px solid red"+ allowtransparency+ ></iframe>+ </body>+ </html>+ `;+}diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.tsindex 923e9079777..fb1b31a47c9 100644--- a/e2e/support/helpers/index.ts+++ b/e2e/support/helpers/index.ts@@ -23,6 +23,7 @@ export * from "./e2e-dragndrop-helpers";export * from "./e2e-element-visibility-helpers";export * from "./e2e-email-helpers";export * from "./e2e-embedding-helpers";+export * from "./e2e-embedding-iframe-interactive-helpers";export * from "./e2e-embedding-iframe-sdk-helpers";export * from "./e2e-embedding-sdk-assertion-helpers";export * from "./e2e-enterprise-helpers";diff --git a/e2e/test/scenarios/embedding/interactive-embedding.cy.spec.js b/e2e/test/scenarios/embedding/interactive-embedding.cy.spec.jsindex 3434889bf0e..93b80c5745f 100644--- a/e2e/test/scenarios/embedding/interactive-embedding.cy.spec.js+++ b/e2e/test/scenarios/embedding/interactive-embedding.cy.spec.js@@ -1590,6 +1590,89 @@ describe("scenarios > embedding > full app", () => {);});+ describe("navigation through postMessage", () => {+ const assertIsLost = () => {+ cy.get("@iframeBody")+ .find("[role=status]")+ .should("contain", "We're a little lost");+ };++ const assertIsDashboard = () => {+ cy.get("@iframeBody")+ .find("[data-testid=table-footer]")+ .should("contain", "Showing first 2,000 rows");+ };++ const assertIsQuestion = () => {+ cy.get("@iframeBody")+ .find("[data-testid=question-row-count]")+ .should("contain", "Showing first 2,000 rows");+ };++ const goTo = (url) => {+ H.postMessageToIframe({+ iframeSelector: 'iframe[src*="localhost:4000/dashboard"]',+ messageData: {+ metabase: { type: "location", location: url },+ },+ });+ };++ it("should handle invalid questions/dashboards (metabase#65500)", () => {+ cy.signInAsAdmin();++ H.createDashboardWithTabs({+ dashboard: {+ name: "Dashboard with tabs",+ },+ dashcards: [+ createMockDashboardCard({+ card_id: ORDERS_QUESTION_ID,+ size_x: 10,+ size_y: 8,+ }),+ ],+ }).then((dashboard) => {+ H.loadInteractiveIframeEmbedTestPage({+ dashboardId: dashboard.id,+ iframeSelector: 'iframe[src*="localhost:4000/dashboard"]',+ });++ cy.get('iframe[src*="localhost:4000/dashboard"]')+ .its("0.contentDocument.body")+ .should("not.be.empty")+ .then(cy.wrap)+ .as("iframeBody");++ assertIsDashboard();++ // invalid dashboard -> valid dashboard+ goTo("/dashboard/9999990");+ assertIsLost();+ goTo(`/dashboard/${dashboard.id}`);+ assertIsDashboard();++ // invalid question -> valid question+ goTo("/question/9999990");+ assertIsLost();+ goTo(`/question/${ORDERS_QUESTION_ID}`);+ assertIsQuestion();++ // invalid question -> valid dashboard+ goTo("/question/9999990");+ assertIsLost();+ goTo(`/dashboard/${dashboard.id}`);+ assertIsDashboard();++ // invalid dashboard -> valid question+ goTo("/dashboard/9999990");+ assertIsLost();+ goTo(`/question/${ORDERS_QUESTION_ID}`);+ assertIsQuestion();+ });+ });+ });+it("should send `frame` message with dashboard height when the dashboard is resized (metabase#37437)", () => {const TAB_1 = { id: 1, name: "Tab 1" };const TAB_2 = { id: 2, name: "Tab 2" };diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsxindex 34cc95f7886..573ef55bc66 100644--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx@@ -25,6 +25,7 @@ import { DashboardContextProvider } from "metabase/dashboard/context";import { useDashboardUrlQuery } from "metabase/dashboard/hooks";import { useAutoScrollToDashcard } from "metabase/dashboard/hooks/use-auto-scroll-to-dashcard";import { parseHashOptions, stringifyHashOptions } from "metabase/lib/browser";+import { isWithinIframe } from "metabase/lib/dom";import { useDispatch, useSelector } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";import { setErrorPage } from "metabase/redux/app";@@ -147,6 +148,11 @@ export const DashboardApp = ({const { autoScrollToDashcardId, reportAutoScrolledToDashcard } =useAutoScrollToDashcard(location);+ const isRouteInSync = window.location.pathname === location.pathname;+ if (isWithinIframe() && !isRouteInSync) {+ return null; // Don't render until route syncs (metabase#65500)+ }+return (<ErrorBoundary message={error}><DashboardContextProviderdiff --git a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsx b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsxindex bf1c2bc1fac..dc22eb5c1e3 100644--- a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsx+++ b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsx@@ -1,3 +1,4 @@+import isPropValid from "@emotion/is-prop-valid";// eslint-disable-next-line no-restricted-importsimport { css } from "@emotion/react";// eslint-disable-next-line no-restricted-imports@@ -39,6 +40,7 @@ export const SearchInputContainer = styled.div<{}return css`background-color: var(--mb-color-bg-white);+&:hover {background-color: var(--mb-color-bg-light);}@@ -116,7 +118,7 @@ export const SearchInput = styled.input<{const ICON_MARGIN = "10px";-export const SearchIcon = styled(Icon)<{+export const SearchIcon = styled(Icon, { shouldForwardProp: isPropValid })<{isActive: boolean;}>`flex-basis: 1rem;diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsxindex a2967b14f84..5701f8b2377 100644--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx@@ -18,6 +18,7 @@ import Bookmark from "metabase/entities/bookmarks";import Timelines from "metabase/entities/timelines";import title from "metabase/hoc/Title";import titleWithLoadingTime from "metabase/hoc/TitleWithLoadingTime";+import { isWithinIframe } from "metabase/lib/dom";import { connect, useSelector } from "metabase/lib/redux";import { closeNavbar } from "metabase/redux/app";import { getIsNavbarOpen } from "metabase/selectors/app";@@ -324,6 +325,10 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {const handleSave = useSaveQuestion({ scheduleCallback });useMount(() => {+ const isRouteInSync = window.location.pathname === location.pathname;+ if (isWithinIframe() && !isRouteInSync) {+ return null; // Don't initialize query builder until route syncs (metabase#65500)+ }initializeQB(location, params);});