A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
add placeholder images for external iframes on export to pdf (#8003)
Shahmir Varqha4ca2888b24a4
diff --git a/frontend/src/utils/__tests__/iframe.test.ts b/frontend/src/utils/__tests__/iframe.test.tsnew file mode 100644index 0000000000..5574c4b66f--- /dev/null+++ b/frontend/src/utils/__tests__/iframe.test.ts@@ -0,0 +1,139 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { captureIframeAsImage } from "../iframe";++// Mock html-to-image+vi.mock("html-to-image", () => ({+ toPng: vi.fn().mockResolvedValue("data:image/png;base64,mock"),+}));++describe("captureIframeAsImage", () => {+ const originalCreateElement = document.createElement.bind(document);++ beforeEach(() => {+ // Mock devicePixelRatio+ Object.defineProperty(window, "devicePixelRatio", {+ value: 1,+ writable: true,+ });++ // Mock canvas for placeholder generation+ vi.spyOn(document, "createElement").mockImplementation((tagName) => {+ const element = originalCreateElement(tagName);+ if (tagName === "canvas") {+ const mockCtx = {+ scale: vi.fn(),+ fillStyle: "",+ fillRect: vi.fn(),+ strokeStyle: "",+ strokeRect: vi.fn(),+ font: "",+ textAlign: "",+ textBaseline: "",+ fillText: vi.fn(),+ measureText: vi.fn().mockReturnValue({ width: 10 }),+ };+ vi.spyOn(element as HTMLCanvasElement, "getContext").mockReturnValue(+ mockCtx as unknown as CanvasRenderingContext2D,+ );+ vi.spyOn(element as HTMLCanvasElement, "toDataURL").mockReturnValue(+ "data:image/png;base64,placeholder",+ );+ }+ return element;+ });+ });++ afterEach(() => {+ vi.clearAllMocks();+ vi.restoreAllMocks();+ });++ it("should return null when element has no iframe", async () => {+ const element = document.createElement("div");+ element.innerHTML = "<p>No iframe here</p>";++ const result = await captureIframeAsImage(element);+ expect(result).toBeNull();+ });++ it("should return placeholder for external iframe", async () => {+ const element = document.createElement("div");+ element.innerHTML = '<iframe src="https://external.com/page"></iframe>';++ const result = await captureIframeAsImage(element);++ expect(result).not.toBeNull();+ expect(result).toMatch(/^data:image\/png;base64,/);+ });++ it("should return placeholder for cross-origin iframe", async () => {+ const element = document.createElement("div");+ element.innerHTML =+ '<iframe src="https://www.openstreetmap.org/export/embed.html"></iframe>';++ const result = await captureIframeAsImage(element);++ expect(result).not.toBeNull();+ expect(result).toMatch(/^data:image\/png;base64,/);+ });++ it("should return null for about:blank iframe without body", async () => {+ const element = document.createElement("div");+ const iframe = document.createElement("iframe");+ iframe.src = "about:blank";+ element.append(iframe);++ // The iframe has no body accessible in jsdom+ const result = await captureIframeAsImage(element);++ // In jsdom, contentDocument may not be accessible+ expect(result).toBeNull();+ });++ it("should handle iframe with relative same-origin src", async () => {+ const element = document.createElement("div");+ element.innerHTML = '<iframe src="./@file/123.html"></iframe>';++ // Same-origin relative URL, but contentDocument not accessible in jsdom+ const result = await captureIframeAsImage(element);++ // Returns null because jsdom can't access contentDocument for file URLs+ expect(result).toBeNull();+ });++ it("should detect external URL from various formats", async () => {+ const externalUrls = [+ "https://example.com",+ "http://external.org/path",+ "https://sub.domain.com:8080/page",+ ];++ for (const url of externalUrls) {+ const element = document.createElement("div");+ element.innerHTML = `<iframe src="${url}"></iframe>`;++ const result = await captureIframeAsImage(element);++ expect(result).not.toBeNull();+ expect(result).toMatch(/^data:image\/png;base64,/);+ }+ });++ it("should not treat same-origin URLs as external", async () => {+ // Same-origin URLs - these should try to capture, not return placeholder+ const sameOriginUrls = ["/local/path", "./relative/path", "../parent/path"];++ for (const url of sameOriginUrls) {+ const element = document.createElement("div");+ element.innerHTML = `<iframe src="${url}"></iframe>`;++ const result = await captureIframeAsImage(element);++ // In jsdom, these return null because contentDocument isn't accessible+ // but they should NOT return a placeholder (which would indicate external detection)+ // The key is they don't trigger the external URL path+ expect(result).toBeNull();+ }+ });+});diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.tsindex d3565ed995..182f508bed 100644--- a/frontend/src/utils/download.ts+++ b/frontend/src/utils/download.ts@@ -7,6 +7,7 @@ import { Filenames } from "@/utils/filenames";import { Paths } from "@/utils/paths";import { prettyError } from "./errors";import { toPng } from "./html-to-image";+import { captureIframeAsImage } from "./iframe";import { Logger } from "./Logger";/**@@ -104,6 +105,12 @@ export async function getImageDataUrlForCell(if (!element) {return;}++ const iframeDataUrl = await captureIframeAsImage(element);+ if (iframeDataUrl) {+ return iframeDataUrl;+ }+const cleanup = prepareCellElementForScreenshot(element, enablePrintMode);try {@@ -125,6 +132,13 @@ export async function downloadCellOutputAsImage(return;}+ // Cell outputs that are iframes+ const iframeDataUrl = await captureIframeAsImage(element);+ if (iframeDataUrl) {+ downloadByURL(iframeDataUrl, Filenames.toPNG(filename));+ return;+ }+await downloadHTMLAsImage({element,filename,diff --git a/frontend/src/utils/iframe.ts b/frontend/src/utils/iframe.tsnew file mode 100644index 0000000000..51850c7b09--- /dev/null+++ b/frontend/src/utils/iframe.ts@@ -0,0 +1,142 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { toPng } from "./html-to-image";++const PLACEHOLDER_WIDTH = 320;+const PLACEHOLDER_HEIGHT = 180;++function isExternalUrl(src: string | null): string | null {+ if (!src || src === "about:blank") {+ return null;+ }+ try {+ const resolved = new URL(src, window.location.href);+ if (resolved.origin === window.location.origin) {+ return null;+ }+ return resolved.href;+ } catch {+ return src;+ }+}++function wrapText(+ ctx: CanvasRenderingContext2D,+ text: string,+ maxWidth: number,+): string[] {+ const lines: string[] = [];+ let current = "";++ for (const char of text) {+ const test = current + char;+ if (ctx.measureText(test).width <= maxWidth) {+ current = test;+ } else {+ if (current) {+ lines.push(current);+ }+ current = char;+ }+ }+ if (current) {+ lines.push(current);+ }++ return lines;+}++function createPlaceholderImage(url: string | null): string {+ const scale = window.devicePixelRatio || 1;+ const canvas = document.createElement("canvas");+ canvas.width = PLACEHOLDER_WIDTH * scale;+ canvas.height = PLACEHOLDER_HEIGHT * scale;++ const ctx = canvas.getContext("2d");+ if (!ctx) {+ return canvas.toDataURL("image/png");+ }++ ctx.scale(scale, scale);++ // Background+ ctx.fillStyle = "#f3f4f6";+ ctx.fillRect(0, 0, PLACEHOLDER_WIDTH, PLACEHOLDER_HEIGHT);++ // Border+ ctx.strokeStyle = "#d1d5db";+ ctx.strokeRect(0.5, 0.5, PLACEHOLDER_WIDTH - 1, PLACEHOLDER_HEIGHT - 1);++ // Text+ ctx.fillStyle = "#6b7280";+ ctx.font = "8px sans-serif";+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";++ const lineHeight = 14;+ const padding = 16;+ const maxWidth = PLACEHOLDER_WIDTH - padding * 2;++ const message = "External iframe";+ const urlLines = url ? wrapText(ctx, url, maxWidth) : [];+ const totalLines = 1 + urlLines.length;+ const totalHeight = totalLines * lineHeight;+ let y = (PLACEHOLDER_HEIGHT - totalHeight) / 2 + lineHeight / 2;++ ctx.fillText(message, PLACEHOLDER_WIDTH / 2, y);+ y += lineHeight;++ for (const line of urlLines) {+ ctx.fillText(line, PLACEHOLDER_WIDTH / 2, y);+ y += lineHeight;+ }++ return canvas.toDataURL("image/png");+}++/**+ * Capture an iframe as a PNG image. We need to do this because external iframes are not supported by html-to-image.+ * @param element - The element to capture the iframe from+ * @returns The image data URL of the iframe, or a placeholder image if the iframe is external+ */+export async function captureIframeAsImage(+ element: HTMLElement,+): Promise<string | null> {+ const iframe = element.querySelector("iframe");+ if (!iframe) {+ return null;+ }++ // Check if the iframe itself is external+ const externalUrl = isExternalUrl(iframe.getAttribute("src"));+ if (externalUrl) {+ return createPlaceholderImage(externalUrl);+ }++ // Try to access iframe document and check for nested external iframes+ let doc: Document;+ try {+ const d = iframe.contentDocument || iframe.contentWindow?.document;+ if (!d?.body) {+ return null;+ }+ doc = d;+ } catch {+ return createPlaceholderImage(null);+ }++ // Check for nested external iframes+ for (const nested of doc.querySelectorAll("iframe")) {+ const nestedExternal = isExternalUrl(nested.getAttribute("src"));+ if (nestedExternal) {+ return createPlaceholderImage(nestedExternal);+ }+ }++ // Capture the iframe content+ try {+ return await toPng(doc.body);+ } catch {+ return createPlaceholderImage(null);+ }+}diff --git a/marimo/_smoke_tests/pdf_export/basic_example.py b/marimo/_smoke_tests/pdf_export/basic_example.pyindex 12dbef4acd..5c725ba367 100644--- a/marimo/_smoke_tests/pdf_export/basic_example.py+++ b/marimo/_smoke_tests/pdf_export/basic_example.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.19.2"+__generated_with = "0.19.6"app = marimo.App(auto_download=["ipynb"])@@ -75,6 +75,46 @@ def _(df, plt):return+def _(mo):+ iframe = mo.iframe("""+ <div style='border: 2px solid #4CAF50; padding: 20px; border-radius: 10px; background: linear-gradient(135deg, #e0f7fa, #80deea);'>+ <h1 style='color: #00796b; font-family: Arial, sans-serif;'>Welcome to My Interactive Frame</h1>+ <p style='font-size: 16px; color: #004d40;'>This is a more complex div element with styled borders, gradients, and custom fonts.</p>+ <ul style='color: #004d40;'>+ <li>Feature 1: Stylish layout</li>+ <li>Feature 2: Custom fonts and colors</li>+ <li>Feature 3: Rounded corners and padding</li>+ </ul>+ <button style='background-color: #00796b; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;' onclick="alert('Button clicked!')">Click Me</button>+ </div>+ """)+ iframe+ return (iframe,)+++def _(iframe, mo):+ mo.Html(iframe.text)+ return+++def _(mo):+ mo.iframe(+ '<iframe src="demo_iframe.html" height="200" width="300" title="Iframe Example"></iframe>'+ )+ return+++def _(mo):+ mo.iframe(+ '<iframe id="inlineFrameExample" title="Inline Frame Example" width="800" height="600" src="https://www.openstreetmap.org/export/embed.html?bbox=-0.004017949104309083%2C51.47612752641776%2C0.00030577182769775396%2C51.478569861898606&layer=mapnik"></iframe>'+ )+ return++@app.celldef _(df):df