Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(toolbar): stop broken assets and slow hosts breaking heatmap saves (#113471)

Jordan Mryyan6365847d3d9c
diff --git a/docs/internal/toolbar-entitlements.md b/docs/internal/toolbar-entitlements.md
index 1cc03e7f046d..768939d5c2c7 100644
--- a/docs/internal/toolbar-entitlements.md
+++ b/docs/internal/toolbar-entitlements.md
@@ -31,3 +31,19 @@ Object-level editor access alone does not allow changing either URL.
Saving again retries all configured page widths and creates a new heatmap.
It does not add missing widths to an existing heatmap.
+
+## Screenshot capture
+
+Saving a heatmap uses the browser's current page to capture screenshots at several widths.
+Screenshots are JPEG images on a white background.
+Web fonts the page uses are embedded at every width.
+Canvases keep their size at every width.
+Images and video posters that cannot load, cannot decode, or answer with an error status such as 403 leave blank areas without changing the layout.
+Unreadable canvases and video frames also leave their original space in the screenshot.
+Image, font, and stylesheet fetches share a 15-second deadline for each capture.
+Stylesheets that miss this deadline are skipped so later capture widths can continue.
+This deadline does not bound the whole rendering process.
+An image that is still loading when a width finishes waiting stays blank at that width and every later width, so one slow host delays a save once instead of at every width.
+Capturing never changes the page's own stylesheets.
+Failed resource fetches are not cached, so later widths and save attempts can load a recovered resource.
+Successfully loaded resources remain cached.
diff --git a/frontend/src/lib/utils/captureElementImage.test.ts b/frontend/src/lib/utils/captureElementImage.test.ts
index 5dd267ed0d17..2dc8cc463c49 100644
--- a/frontend/src/lib/utils/captureElementImage.test.ts
+++ b/frontend/src/lib/utils/captureElementImage.test.ts
@@ -1,6 +1,6 @@
import { toBlob } from 'html-to-image'
-import { captureElementImage } from './captureElementImage'
+import { BLANK_IMAGE, captureElementImage } from './captureElementImage'
jest.mock('html-to-image', () => ({
toBlob: jest.fn(() => Promise.resolve(new Blob(['png'], { type: 'image/png' }))),
@@ -16,4 +16,28 @@ describe('captureElementImage', () => {
expect(includeStyleProperties).not.toBeUndefined()
expect(includeStyleProperties.filter((name: string) => name.startsWith('--'))).toEqual([])
})
+
+ it('keys images by query string and degrades broken assets to a placeholder', async () => {
+ await captureElementImage(document.createElement('div'))
+
+ expect(toBlob).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ includeQueryParams: true, imagePlaceholder: BLANK_IMAGE })
+ )
+ })
+
+ it('bounds the resource fetches so a stalled asset cannot hang the capture', async () => {
+ jest.useFakeTimers()
+ try {
+ await captureElementImage(document.createElement('div'))
+
+ const { fetchRequestInit } = (toBlob as jest.Mock).mock.calls[0][1]
+ expect(fetchRequestInit.signal.aborted).toBe(false)
+
+ await jest.advanceTimersByTimeAsync(15000)
+ expect(fetchRequestInit.signal.aborted).toBe(true)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
})
diff --git a/frontend/src/lib/utils/captureElementImage.ts b/frontend/src/lib/utils/captureElementImage.ts
index 6971fa2626e2..ddef8e7f74e4 100644
--- a/frontend/src/lib/utils/captureElementImage.ts
+++ b/frontend/src/lib/utils/captureElementImage.ts
@@ -27,10 +27,18 @@ function getStylePropertyNames(): string[] {
return names
}
+export const BLANK_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
+
+const RESOURCE_FETCH_TIMEOUT_MS = 15000
+
/** Rasterizes a live DOM element to an image blob. Throws when the element renders to nothing. */
export async function captureElementImage(element: HTMLElement, options?: CaptureImageOptions): Promise<Blob> {
const blob = await toBlob(element, {
includeStyleProperties: getStylePropertyNames(),
+ includeQueryParams: true,
+ imagePlaceholder: BLANK_IMAGE,
+ onImageErrorHandler: () => {},
+ fetchRequestInit: { signal: AbortSignal.timeout(RESOURCE_FETCH_TIMEOUT_MS) },
...options,
})
diff --git a/frontend/src/lib/utils/htmlToImagePatch.test.ts b/frontend/src/lib/utils/htmlToImagePatch.test.ts
index 3a0d2d73f98a..8237b87756ad 100644
--- a/frontend/src/lib/utils/htmlToImagePatch.test.ts
+++ b/frontend/src/lib/utils/htmlToImagePatch.test.ts
@@ -1,7 +1,12 @@
import { readFileSync } from 'fs'
-import { resolveUrl } from 'html-to-image/lib/util'
+import { getFontEmbedCSS, toBlob } from 'html-to-image'
+import { cloneNode } from 'html-to-image/lib/clone-node'
+import { resourceToDataURL } from 'html-to-image/lib/dataurl'
+import * as imageUtils from 'html-to-image/lib/util'
import { dirname, join } from 'path'
+import { BLANK_IMAGE } from './captureElementImage'
+
// html-to-image resolves a relative `url()` inside @font-face against the stylesheet's own href.
// Upstream does that by building a detached document, putting a <base href> in it and reading back
// a resolved anchor. Chromium judges that assignment against `base-uri`, so under our policy the
@@ -28,8 +33,127 @@ import { dirname, join } from 'path'
// so nothing in this repo loads it.
describe('html-to-image patch', () => {
const packageRoot = dirname(dirname(require.resolve('html-to-image')))
+ afterEach(() => {
+ jest.restoreAllMocks()
+ document.body.innerHTML = ''
+ })
+
const STYLESHEET = 'https://app-static-prod.posthog.com/static/index-46THL72U.css'
+ function imageBlob(content: string): Blob {
+ const iframe = document.createElement('iframe')
+ document.body.appendChild(iframe)
+ const { Blob: RealmBlob } = iframe.contentWindow as Window & typeof globalThis
+ return new RealmBlob([content], { type: 'image/png' })
+ }
+
+ function response(status: number, content = '<html>'): Response {
+ return { ok: status < 400, status, headers: new Headers(), blob: async () => imageBlob(content) } as Response
+ }
+
+ function stubImageLoading(decode: () => Promise<void>): void {
+ jest.spyOn(window, 'Image').mockImplementation(() => {
+ const img = document.createElement('img')
+ img.decode = decode
+ Object.defineProperty(img, 'src', {
+ set: () => setTimeout(() => img.dispatchEvent(new Event('load'))),
+ })
+ return img
+ })
+ }
+
+ it.each([
+ [
+ 'video with an undecodable poster',
+ (createImage: jest.SpyInstance): HTMLElement => {
+ createImage.mockRejectedValueOnce(new Event('error'))
+ const video = document.createElement('video')
+ video.poster = 'data:image/png;base64,aW52YWxpZA=='
+ return video
+ },
+ ],
+ [
+ 'video with an unreadable frame',
+ (): HTMLElement => {
+ const video = document.createElement('video')
+ Object.defineProperty(video, 'currentSrc', { value: 'https://example.com/video.mp4' })
+ jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null)
+ jest.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockImplementation(() => {
+ throw new DOMException('Canvas is tainted', 'SecurityError')
+ })
+ return video
+ },
+ ],
+ ])('keeps the box of a %s', async (_label, buildElement) => {
+ const image = document.createElement('img')
+ const createImage = jest.spyOn(imageUtils, 'createImage').mockResolvedValue(image)
+ jest.spyOn(console, 'error').mockImplementation(() => {})
+ const element = buildElement(createImage)
+ element.style.cssText = 'width: 240px; height: 120px; display: block'
+
+ const clone = await cloneNode(element, {
+ imagePlaceholder: BLANK_IMAGE,
+ includeStyleProperties: ['width', 'height', 'display'],
+ })
+
+ expect(clone).toBe(image)
+ expect(image.style.width).toBe('240px')
+ expect(image.style.height).toBe('120px')
+ expect(image.style.display).toBe('block')
+ expect(createImage).toHaveBeenLastCalledWith(BLANK_IMAGE)
+ })
+
+ it('replaces a tainted canvas with a blank image of the same size', async () => {
+ jest.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockImplementation(function (this: HTMLCanvasElement) {
+ return `data:image/png;blank-${this.width}x${this.height}`
+ })
+ const canvas = document.createElement('canvas')
+ canvas.width = 240
+ canvas.height = 120
+ Object.defineProperty(canvas, 'toDataURL', {
+ value: () => {
+ throw new DOMException('Canvas is tainted', 'SecurityError')
+ },
+ })
+ const image = document.createElement('img')
+ const createImage = jest.spyOn(imageUtils, 'createImage').mockResolvedValue(image)
+
+ await expect(cloneNode(canvas, {})).resolves.toBe(image)
+ expect(createImage).toHaveBeenCalledWith('data:image/png;blank-240x120')
+ })
+
+ it.each([
+ ['import', (href: string): CSSRule[] => [{ type: CSSRule.IMPORT_RULE, href } as CSSImportRule]],
+ [
+ 'cross-origin',
+ (): CSSRule[] => {
+ throw new DOMException('Cross-origin stylesheet', 'SecurityError')
+ },
+ ],
+ ])('settles an aborted %s stylesheet fetch', async (kind, readRules) => {
+ const controller = new AbortController()
+ const node = document.createElement('div')
+ const sheet = {
+ href: `https://example.com/${kind}.css`,
+ get cssRules(): CSSRule[] {
+ return readRules(this.href)
+ },
+ }
+ Object.defineProperty(node, 'ownerDocument', { value: { styleSheets: [sheet] } })
+ jest.spyOn(console, 'error').mockImplementation(() => {})
+ jest.spyOn(global, 'fetch').mockImplementation(
+ (_url, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true })
+ })
+ )
+
+ const result = getFontEmbedCSS(node, { fetchRequestInit: { signal: controller.signal } })
+ controller.abort()
+
+ await expect(result).resolves.toBe('')
+ })
+
// Expectations are written out rather than computed, so the assertion does not restate the
// implementation it is checking.
it.each([
@@ -42,7 +166,7 @@ describe('html-to-image patch', () => {
['parent segment', '../assets/Inter.woff2', 'https://app-static-prod.posthog.com/assets/Inter.woff2'],
['absolute, returned untouched', 'https://cdn.example.com/Inter.woff2', 'https://cdn.example.com/Inter.woff2'],
])('resolves a %s font URL against the stylesheet', (_label, url, expected) => {
- expect(resolveUrl(url, STYLESHEET)).toBe(expected)
+ expect(imageUtils.resolveUrl(url, STYLESHEET)).toBe(expected)
})
it.each(['es/util.js', 'lib/util.js'])('does not assign <base href> on a detached document in %s', (file) => {
@@ -50,4 +174,111 @@ describe('html-to-image patch', () => {
expect(source).not.toMatch(/createElement\(['"]base['"]\)/)
})
+
+ it.each([
+ [
+ 'a rejected fetch',
+ 'rejected',
+ (): Promise<Response> => Promise.reject(new DOMException('Unavailable', 'AbortError')),
+ ],
+ ['a 403 error page', 'forbidden', async (): Promise<Response> => response(403)],
+ ['a 500 error page', 'server-error', async (): Promise<Response> => response(500)],
+ ])(
+ 'uses the placeholder for %s and retries the image without caching the placeholder',
+ async (_label, name, failure) => {
+ const url = `https://example.com/${name}.png`
+ const fetch = jest
+ .spyOn(global, 'fetch')
+ .mockImplementationOnce(failure)
+ .mockResolvedValue(response(200, 'recovered'))
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
+
+ const load = (): Promise<string> => resourceToDataURL(url, 'image/png', { imagePlaceholder: BLANK_IMAGE })
+
+ expect(await load()).toBe(BLANK_IMAGE)
+ expect(await load()).toBe('data:image/png;base64,cmVjb3ZlcmVk')
+ expect(await load()).toBe('data:image/png;base64,cmVjb3ZlcmVk')
+ expect(fetch).toHaveBeenCalledTimes(2)
+ }
+ )
+
+ it('embeds a font from an unreadable stylesheet without writing into the page stylesheets', async () => {
+ const pageStyle = document.createElement('style')
+ pageStyle.textContent = 'body { margin: 0 }'
+ document.head.appendChild(pageStyle)
+ const pageSheet = pageStyle.sheet as CSSStyleSheet
+ const crossOriginSheet = {
+ href: 'https://fonts.example.com/unreadable.css',
+ get cssRules(): CSSRule[] {
+ throw new DOMException('Cross-origin stylesheet', 'SecurityError')
+ },
+ }
+ const node = document.createElement('div')
+ node.innerHTML = '<span style="font-family: Fancy">x</span>'
+ Object.defineProperty(node, 'ownerDocument', { value: { styleSheets: [pageSheet, crossOriginSheet] } })
+ jest.spyOn(console, 'error').mockImplementation(() => {})
+ jest.spyOn(global, 'fetch').mockImplementation(async (url) =>
+ String(url).endsWith('.css')
+ ? ({
+ ok: true,
+ status: 200,
+ text: async () => '@font-face { font-family: Fancy; src: url(fancy.woff2) format("woff2") }',
+ } as Response)
+ : response(200, 'font')
+ )
+
+ const css = await getFontEmbedCSS(node, {})
+
+ expect(css).toContain('font-family: Fancy')
+ expect(css).toContain('Zm9udA==')
+ expect(pageSheet.cssRules).toHaveLength(1)
+ pageStyle.remove()
+ })
+
+ it('finds the fonts of an element that lives in another document', async () => {
+ const iframe = document.createElement('iframe')
+ document.body.appendChild(iframe)
+ const doc = iframe.contentDocument as Document
+ const style = doc.createElement('style')
+ style.textContent = '@font-face { font-family: Fancy; src: url(data:font/woff2;base64,AAAA) format("woff2") }'
+ doc.head.appendChild(style)
+ const root = doc.createElement('div')
+ root.innerHTML = '<header><span style="font-family: Fancy">Heading</span></header>'
+ doc.body.appendChild(root)
+
+ await expect(getFontEmbedCSS(root, {})).resolves.toContain('font-family: Fancy')
+ })
+
+ it('settles createImage when decode() rejects after the image loaded', async () => {
+ stubImageLoading(() => Promise.reject(new DOMException('Decode failed', 'EncodingError')))
+
+ await expect(imageUtils.createImage('https://example.com/huge.svg')).resolves.toMatchObject({ tagName: 'IMG' })
+ })
+
+ it('encodes the blob in the requested type and quality', async () => {
+ Object.defineProperty(window, 'SVGImageElement', { value: class {}, configurable: true })
+ try {
+ jest.spyOn(imageUtils, 'createImage').mockResolvedValue(document.createElement('img'))
+ jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ drawImage: () => {},
+ fillRect: () => {},
+ } as never)
+ const encode = jest
+ .spyOn(HTMLCanvasElement.prototype, 'toBlob')
+ .mockImplementation((callback, type) => callback(new Blob([], { type })))
+
+ const blob = await toBlob(document.createElement('div'), {
+ type: 'image/jpeg',
+ quality: 0.7,
+ width: 10,
+ height: 10,
+ skipFonts: true,
+ })
+
+ expect(blob?.type).toBe('image/jpeg')
+ expect(encode).toHaveBeenCalledWith(expect.any(Function), 'image/jpeg', 0.7)
+ } finally {
+ delete (window as Partial<typeof window>).SVGImageElement
+ }
+ })
})
diff --git a/frontend/src/toolbar/utils/responsiveScreenshot.test.ts b/frontend/src/toolbar/utils/responsiveScreenshot.test.ts
index b965dda62972..74322d655d46 100644
--- a/frontend/src/toolbar/utils/responsiveScreenshot.test.ts
+++ b/frontend/src/toolbar/utils/responsiveScreenshot.test.ts
@@ -1,3 +1,5 @@
+import { BLANK_IMAGE } from 'lib/utils/captureElementImage'
+
import { captureResponsiveScreenshots } from '~/toolbar/utils/responsiveScreenshot'
jest.mock('~/toolbar/utils/screenshot', () => ({
@@ -10,16 +12,21 @@ jest.mock('~/toolbar/toolbarLogger', () => ({
toolbarLogger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
}))
+const { captureElementScreenshot } = jest.requireMock('~/toolbar/utils/screenshot')
const { captureToolbarException } = jest.requireMock('~/toolbar/toolbarPosthogJS')
const { toolbarLogger } = jest.requireMock('~/toolbar/toolbarLogger')
describe('captureResponsiveScreenshots', () => {
beforeEach(() => {
jest.useFakeTimers()
+ ;(captureElementScreenshot as jest.Mock).mockImplementation(() => Promise.reject(new Error('capture failed')))
;(captureToolbarException as jest.Mock).mockClear()
;(toolbarLogger.warn as jest.Mock).mockClear()
})
- afterEach(() => jest.useRealTimers())
+ afterEach(() => {
+ jest.useRealTimers()
+ document.body.innerHTML = ''
+ })
it('skips every failed width and resolves to an empty array instead of throwing', async () => {
const onProgress = jest.fn()
@@ -44,4 +51,22 @@ describe('captureResponsiveScreenshots', () => {
requested_count: 3,
})
})
+
+ it('waits for a stalled image once and leaves it blank at every width', async () => {
+ const image = document.createElement('img')
+ image.src = 'https://example.com/stalled.png'
+ document.body.appendChild(image)
+ const capturedSources: (string | null)[] = []
+ ;(captureElementScreenshot as jest.Mock).mockImplementation(async (element: HTMLElement) => {
+ capturedSources.push(element.querySelector('img')?.getAttribute('src') ?? null)
+ return new Blob()
+ })
+
+ const started = Date.now()
+ const elapsed = captureResponsiveScreenshots([320, 768, 1440]).then(() => Date.now() - started)
+ await jest.runAllTimersAsync()
+
+ expect(await elapsed).toBeLessThan(2 * 4000)
+ expect(capturedSources).toEqual([BLANK_IMAGE, BLANK_IMAGE, BLANK_IMAGE])
+ })
})
diff --git a/frontend/src/toolbar/utils/responsiveScreenshot.ts b/frontend/src/toolbar/utils/responsiveScreenshot.ts
index 5f8a8cc3a5c3..135440862149 100644
--- a/frontend/src/toolbar/utils/responsiveScreenshot.ts
+++ b/frontend/src/toolbar/utils/responsiveScreenshot.ts
@@ -1,4 +1,5 @@
import { delay } from 'lib/utils/async'
+import { BLANK_IMAGE } from 'lib/utils/captureElementImage'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'
@@ -9,6 +10,8 @@ export const RESPONSIVE_CAPTURE_WIDTHS = [320, 375, 425, 768, 1024, 1440, 1920]
const PER_WIDTH_SETTLE_TIMEOUT_MS = 4000
+const CANVAS_SIZE_ATTR = 'data-ph-canvas-size'
+
export interface WidthCapture {
width: number
blob: Blob
@@ -49,14 +52,31 @@ function populateIframe(iframe: HTMLIFrameElement): void {
copyCanvases(doc)
}
+function adoptCanvasSizing(doc: Document, rules: string[]): void {
+ const view = doc.defaultView as (Window & typeof globalThis) | null
+ if (!view || rules.length === 0) {
+ return
+ }
+ try {
+ const sheet = new view.CSSStyleSheet()
+ sheet.replaceSync(rules.join('\n'))
+ doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet]
+ } catch {}
+}
+
function copyCanvases(doc: Document): void {
const liveCanvases = document.querySelectorAll('canvas')
const clonedCanvases = doc.querySelectorAll('canvas')
+ const sizingRules: string[] = []
clonedCanvases.forEach((cloned, index) => {
const live = liveCanvases[index] as HTMLCanvasElement | undefined
if (!live || live.width === 0 || live.height === 0) {
return
}
+ cloned.setAttribute(CANVAS_SIZE_ATTR, String(index))
+ sizingRules.push(
+ `:where([${CANVAS_SIZE_ATTR}="${index}"]) { width: ${live.width}px; aspect-ratio: ${live.width} / ${live.height}; }`
+ )
try {
const clonedCanvas = cloned as HTMLCanvasElement
clonedCanvas.width = live.width
@@ -64,6 +84,7 @@ function copyCanvases(doc: Document): void {
clonedCanvas.getContext('2d')?.drawImage(live, 0, 0)
} catch {}
})
+ adoptCanvasSizing(doc, sizingRules)
}
function waitForResource(el: HTMLLinkElement | HTMLImageElement, isReady: boolean): Promise<void> {
@@ -76,6 +97,29 @@ function waitForResource(el: HTMLLinkElement | HTMLImageElement, isReady: boolea
})
}
+function blankImages(doc: Document, urls: Set<string>): void {
+ for (const image of Array.from(doc.images)) {
+ if (urls.has(image.src)) {
+ image
+ .closest('picture')
+ ?.querySelectorAll('source')
+ .forEach((source) => {
+ source.srcset = ''
+ })
+ image.srcset = ''
+ image.src = BLANK_IMAGE
+ }
+ }
+}
+
+function collectStalledImages(doc: Document, urls: Set<string>): void {
+ for (const image of Array.from(doc.images)) {
+ if (!image.complete && image.loading !== 'lazy') {
+ urls.add(image.src)
+ }
+ }
+}
+
async function waitForSettle(iframe: HTMLIFrameElement): Promise<void> {
const doc = iframe.contentDocument
if (!doc) {
@@ -91,21 +135,28 @@ async function waitForSettle(iframe: HTMLIFrameElement): Promise<void> {
} catch {}
iframe.style.height = `${doc.documentElement.scrollHeight}px`
await delay(150)
- await Promise.all(Array.from(doc.images).map((img) => waitForResource(img, img.complete)))
+ await Promise.all(
+ Array.from(doc.images)
+ .filter((img) => img.src !== BLANK_IMAGE)
+ .map((img) => waitForResource(img, img.complete))
+ )
})()
await Promise.race([settled, delay(PER_WIDTH_SETTLE_TIMEOUT_MS)])
}
-async function captureWidth(width: number): Promise<Blob> {
+async function captureWidth(width: number, stalledImageUrls: Set<string>): Promise<Blob> {
const iframe = buildReflowIframe(width)
try {
populateIframe(iframe)
- await waitForSettle(iframe)
const doc = iframe.contentDocument
if (!doc) {
throw new Error('Reflow iframe document went away')
}
+ blankImages(doc, stalledImageUrls)
+ await waitForSettle(iframe)
+ collectStalledImages(doc, stalledImageUrls)
+ blankImages(doc, stalledImageUrls)
return await captureElementScreenshot(doc.documentElement, {
pixelRatio: 1,
width,
@@ -124,9 +175,10 @@ export async function captureResponsiveScreenshots(
const captures: WidthCapture[] = []
const failures: { width: number; error: Error }[] = []
let attempted = 0
+ const stalledImageUrls = new Set<string>()
for (const width of widths) {
try {
- const blob = await captureWidth(width)
+ const blob = await captureWidth(width, stalledImageUrls)
captures.push({ width, blob })
} catch (e) {
const error = toError(e, `Responsive heatmap capture failed at ${width}px`)
diff --git a/frontend/src/toolbar/utils/screenshot.test.ts b/frontend/src/toolbar/utils/screenshot.test.ts
index 309c27042268..3475766372a4 100644
--- a/frontend/src/toolbar/utils/screenshot.test.ts
+++ b/frontend/src/toolbar/utils/screenshot.test.ts
@@ -31,10 +31,14 @@ describe('captureElementScreenshot', () => {
)
})
- it('returns the blob on success', async () => {
+ it('returns a JPEG on a white background so transparent areas do not turn black', async () => {
const blob = new Blob(['x'], { type: 'image/jpeg' })
mockToBlob.mockResolvedValueOnce(blob)
await expect(captureElementScreenshot(document.documentElement)).resolves.toBe(blob)
+ expect(mockToBlob).toHaveBeenCalledWith(
+ document.documentElement,
+ expect.objectContaining({ type: 'image/jpeg', backgroundColor: '#ffffff' })
+ )
})
})
diff --git a/frontend/src/toolbar/utils/screenshot.ts b/frontend/src/toolbar/utils/screenshot.ts
index b35570c626a4..6cc5b4e9a892 100644
--- a/frontend/src/toolbar/utils/screenshot.ts
+++ b/frontend/src/toolbar/utils/screenshot.ts
@@ -28,6 +28,7 @@ export async function captureElementScreenshot(element: HTMLElement, options?: C
type: 'image/jpeg',
quality: 0.7,
filter: screenshotFilter,
+ backgroundColor: '#ffffff',
...options,
})
} catch (error) {
diff --git a/patches/[email protected] b/patches/[email protected]
index 357cf82aae12..daf7ab82cca3 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -1,5 +1,204 @@
+diff --git a/es/clone-node.js b/es/clone-node.js
+index 114cbf214f65cda237dbba67458c2b68fadf421e..6436f0377161d77ea048e8d451d68f34ccc8d634 100644
+--- a/es/clone-node.js
++++ b/es/clone-node.js
+@@ -2,8 +2,19 @@ import { clonePseudoElements } from './clone-pseudos';
+ import { createImage, toArray, isInstanceOfElement, getStyleProperties, } from './util';
+ import { getMimeType } from './mimes';
+ import { resourceToDataURL } from './dataurl';
++function readCanvasDataURL(canvas) {
++ try {
++ return canvas.toDataURL();
++ }
++ catch (error) {
++ const blank = canvas.ownerDocument.createElement('canvas');
++ blank.width = canvas.width;
++ blank.height = canvas.height;
++ return blank.toDataURL();
++ }
++}
+ async function cloneCanvasElement(canvas) {
+- const dataURL = canvas.toDataURL();
++ const dataURL = readCanvasDataURL(canvas);
+ if (dataURL === 'data:,') {
+ return canvas.cloneNode(false);
+ }
+@@ -41,7 +52,12 @@ async function cloneSingleNode(node, options) {
+ return cloneCanvasElement(node);
+ }
+ if (isInstanceOfElement(node, HTMLVideoElement)) {
+- return cloneVideoElement(node, options);
++ return cloneVideoElement(node, options).catch((error) => {
++ if (options.imagePlaceholder) {
++ return createImage(options.imagePlaceholder);
++ }
++ throw error;
++ });
+ }
+ if (isInstanceOfElement(node, HTMLIFrameElement)) {
+ return cloneIFrameElement(node, options);
+diff --git a/es/dataurl.js b/es/dataurl.js
+index 174e4b9c1f517448661016e619e0d9cbdc645b08..4850558b2d0a0c133f6c8a4e375e57b5da35ba44 100644
+--- a/es/dataurl.js
++++ b/es/dataurl.js
+@@ -9,8 +9,8 @@ export function makeDataUrl(content, mimeType) {
+ }
+ export async function fetchAsDataURL(url, init, process) {
+ const res = await fetch(url, init);
+- if (res.status === 404) {
+- throw new Error(`Resource "${res.url}" not found`);
++ if (!res.ok) {
++ throw new Error(`Resource "${res.url}" responded with ${res.status}`);
+ }
+ const blob = await res.blob();
+ return new Promise((resolve, reject) => {
+@@ -69,6 +69,7 @@ export async function resourceToDataURL(resourceUrl, contentType, options) {
+ if (msg) {
+ console.warn(msg);
+ }
++ return dataURL;
+ }
+ cache[cacheKey] = dataURL;
+ return dataURL;
+diff --git a/es/embed-webfonts.js b/es/embed-webfonts.js
+index f6b0d96829c8a3301c142cacd07079e85b1f64fd..c516c470bf587cc4e1005b067e6d16266829cec0 100644
+--- a/es/embed-webfonts.js
++++ b/es/embed-webfonts.js
+@@ -1,13 +1,13 @@
+-import { toArray } from './util';
++import { toArray, isInstanceOfElement } from './util';
+ import { fetchAsDataURL } from './dataurl';
+ import { shouldEmbed, embedResources } from './embed-resources';
+ const cssFetchCache = {};
+-async function fetchCSS(url) {
++async function fetchCSS(url, options) {
+ let cache = cssFetchCache[url];
+ if (cache != null) {
+ return cache;
+ }
+- const res = await fetch(url);
++ const res = await fetch(url, options.fetchRequestInit);
+ const cssText = await res.text();
+ cache = { url, cssText };
+ cssFetchCache[url] = cache;
+@@ -73,31 +73,46 @@ function parseCSS(source) {
+ }
+ return result;
+ }
++function createDetachedSheet() {
++ try {
++ return new CSSStyleSheet();
++ }
++ catch (e) {
++ const doc = document.implementation.createHTMLDocument('');
++ const style = doc.createElement('style');
++ doc.head.appendChild(style);
++ return style.sheet;
++ }
++}
++function insertFetchedRule(sheet, rule) {
++ if (!sheet || rule.trimStart().startsWith('@import')) {
++ return;
++ }
++ try {
++ sheet.insertRule(rule, sheet.cssRules.length);
++ }
++ catch (error) {
++ console.error('Error inserting rule from remote css', {
++ rule,
++ error,
++ });
++ }
++}
+ async function getCSSRules(styleSheets, options) {
+ const ret = [];
+ const deferreds = [];
++ const fetchedRules = createDetachedSheet();
+ // First loop inlines imports
+ styleSheets.forEach((sheet) => {
+ if ('cssRules' in sheet) {
+ try {
+ toArray(sheet.cssRules || []).forEach((item, index) => {
+ if (item.type === CSSRule.IMPORT_RULE) {
+- let importIndex = index + 1;
+ const url = item.href;
+- const deferred = fetchCSS(url)
++ const deferred = fetchCSS(url, options)
+ .then((metadata) => embedFonts(metadata, options))
+ .then((cssText) => parseCSS(cssText).forEach((rule) => {
+- try {
+- sheet.insertRule(rule, rule.startsWith('@import')
+- ? (importIndex += 1)
+- : sheet.cssRules.length);
+- }
+- catch (error) {
+- console.error('Error inserting rule from remote css', {
+- rule,
+- error,
+- });
+- }
++ insertFetchedRule(fetchedRules, rule);
+ }))
+ .catch((e) => {
+ console.error('Error loading remote css', e.toString());
+@@ -107,12 +122,11 @@ async function getCSSRules(styleSheets, options) {
+ });
+ }
+ catch (e) {
+- const inline = styleSheets.find((a) => a.href == null) || document.styleSheets[0];
+ if (sheet.href != null) {
+- deferreds.push(fetchCSS(sheet.href)
++ deferreds.push(fetchCSS(sheet.href, options)
+ .then((metadata) => embedFonts(metadata, options))
+ .then((cssText) => parseCSS(cssText).forEach((rule) => {
+- inline.insertRule(rule, inline.cssRules.length);
++ insertFetchedRule(fetchedRules, rule);
+ }))
+ .catch((err) => {
+ console.error('Error loading remote stylesheet', err);
+@@ -136,6 +150,9 @@ async function getCSSRules(styleSheets, options) {
+ }
+ }
+ });
++ toArray(fetchedRules ? fetchedRules.cssRules : []).forEach((item) => {
++ ret.push(item);
++ });
+ return ret;
+ });
+ }
+@@ -163,7 +180,7 @@ function getUsedFonts(node) {
+ fonts.add(normalizeFontFamily(font));
+ });
+ Array.from(node.children).forEach((child) => {
+- if (child instanceof HTMLElement) {
++ if (isInstanceOfElement(child, HTMLElement)) {
+ traverse(child);
+ }
+ });
+@@ -175,7 +192,7 @@ export async function getWebFontCSS(node, options) {
+ const rules = await parseWebFontRules(node, options);
+ const usedFonts = getUsedFonts(node);
+ const cssTexts = await Promise.all(rules
+- .filter((rule) => usedFonts.has(normalizeFontFamily(rule.style.fontFamily)))
++ .filter((rule) => usedFonts.has(normalizeFontFamily(rule.style.getPropertyValue('font-family'))))
+ .map((rule) => {
+ const baseUrl = rule.parentStyleSheet
+ ? rule.parentStyleSheet.href
+diff --git a/es/index.js b/es/index.js
+index 0eda9388109fc26752b7df643813f80e135c95e5..270f4a97d4abf0bb1556e3fd7d1039ab7cd93c35 100644
+--- a/es/index.js
++++ b/es/index.js
+@@ -51,7 +51,7 @@ export async function toJpeg(node, options = {}) {
+ }
+ export async function toBlob(node, options = {}) {
+ const canvas = await toCanvas(node, options);
+- const blob = await canvasToBlob(canvas);
++ const blob = await canvasToBlob(canvas, options);
+ return blob;
+ }
+ export async function getFontEmbedCSS(node, options = {}) {
diff --git a/es/util.js b/es/util.js
-index 90a3cd19a6bcc763d98cbd476fde17f4bc0428fa..4c1f1b94da109566bb184e420ed158fdf74fc62d 100644
+index 90a3cd19a6bcc763d98cbd476fde17f4bc0428fa..7c16761d3a1ff11ebb603a3693d74204656e3b4b 100644
--- a/es/util.js
+++ b/es/util.js
@@ -11,16 +11,17 @@ export function resolveUrl(url, baseUrl) {
@@ -29,8 +228,229 @@ index 90a3cd19a6bcc763d98cbd476fde17f4bc0428fa..4c1f1b94da109566bb184e420ed158fd
}
export const uuid = (() => {
// generate uuid for className of pseudo elements.
+@@ -149,7 +150,9 @@ export function createImage(url) {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => {
+- img.decode().then(() => {
++ img.decode()
++ .catch(() => undefined)
++ .then(() => {
+ requestAnimationFrame(() => resolve(img));
+ });
+ };
+diff --git a/lib/clone-node.js b/lib/clone-node.js
+index 214f4d30a50baae7f007d2399eeac298366538c7..a881e63325fbd9d77682164e4919d66d9ec2e79b 100644
+--- a/lib/clone-node.js
++++ b/lib/clone-node.js
+@@ -41,11 +41,22 @@ var clone_pseudos_1 = require("./clone-pseudos");
+ var util_1 = require("./util");
+ var mimes_1 = require("./mimes");
+ var dataurl_1 = require("./dataurl");
++function readCanvasDataURL(canvas) {
++ try {
++ return canvas.toDataURL();
++ }
++ catch (error) {
++ var blank = canvas.ownerDocument.createElement('canvas');
++ blank.width = canvas.width;
++ blank.height = canvas.height;
++ return blank.toDataURL();
++ }
++}
+ function cloneCanvasElement(canvas) {
+ return __awaiter(this, void 0, void 0, function () {
+ var dataURL;
+ return __generator(this, function (_a) {
+- dataURL = canvas.toDataURL();
++ dataURL = readCanvasDataURL(canvas);
+ if (dataURL === 'data:,') {
+ return [2 /*return*/, canvas.cloneNode(false)];
+ }
+@@ -105,7 +116,12 @@ function cloneSingleNode(node, options) {
+ return [2 /*return*/, cloneCanvasElement(node)];
+ }
+ if ((0, util_1.isInstanceOfElement)(node, HTMLVideoElement)) {
+- return [2 /*return*/, cloneVideoElement(node, options)];
++ return [2 /*return*/, cloneVideoElement(node, options).catch(function (error) {
++ if (options.imagePlaceholder) {
++ return (0, util_1.createImage)(options.imagePlaceholder);
++ }
++ throw error;
++ })];
+ }
+ if ((0, util_1.isInstanceOfElement)(node, HTMLIFrameElement)) {
+ return [2 /*return*/, cloneIFrameElement(node, options)];
+diff --git a/lib/dataurl.js b/lib/dataurl.js
+index d0b4141324abeb9a47322f03ee8a297d3bc926cb..ff0e779a94af09fd81dc582fffc777d778c7708c 100644
+--- a/lib/dataurl.js
++++ b/lib/dataurl.js
+@@ -56,8 +56,8 @@ function fetchAsDataURL(url, init, process) {
+ case 0: return [4 /*yield*/, fetch(url, init)];
+ case 1:
+ res = _a.sent();
+- if (res.status === 404) {
+- throw new Error("Resource \"".concat(res.url, "\" not found"));
++ if (!res.ok) {
++ throw new Error("Resource \"".concat(res.url, "\" responded with ").concat(res.status));
+ }
+ return [4 /*yield*/, res.blob()];
+ case 2:
+@@ -132,7 +132,7 @@ function resourceToDataURL(resourceUrl, contentType, options) {
+ if (msg) {
+ console.warn(msg);
+ }
+- return [3 /*break*/, 4];
++ return [2 /*return*/, dataURL];
+ case 4:
+ cache[cacheKey] = dataURL;
+ return [2 /*return*/, dataURL];
+diff --git a/lib/embed-webfonts.js b/lib/embed-webfonts.js
+index c91538bd9c3afa63326a91267fb7b5b9c999cccd..af4d87c9ebe96b1a75bd1091f450d4ec94b00dd2 100644
+--- a/lib/embed-webfonts.js
++++ b/lib/embed-webfonts.js
+@@ -41,7 +41,7 @@ var util_1 = require("./util");
+ var dataurl_1 = require("./dataurl");
+ var embed_resources_1 = require("./embed-resources");
+ var cssFetchCache = {};
+-function fetchCSS(url) {
++function fetchCSS(url, options) {
+ return __awaiter(this, void 0, void 0, function () {
+ var cache, res, cssText;
+ return __generator(this, function (_a) {
+@@ -51,7 +51,7 @@ function fetchCSS(url) {
+ if (cache != null) {
+ return [2 /*return*/, cache];
+ }
+- return [4 /*yield*/, fetch(url)];
++ return [4 /*yield*/, fetch(url, options.fetchRequestInit)];
+ case 1:
+ res = _a.sent();
+ return [4 /*yield*/, res.text()];
+@@ -134,35 +134,50 @@ function parseCSS(source) {
+ }
+ return result;
+ }
++function createDetachedSheet() {
++ try {
++ return new CSSStyleSheet();
++ }
++ catch (e) {
++ var doc = document.implementation.createHTMLDocument('');
++ var style = doc.createElement('style');
++ doc.head.appendChild(style);
++ return style.sheet;
++ }
++}
++function insertFetchedRule(sheet, rule) {
++ if (!sheet || rule.trimStart().startsWith('@import')) {
++ return;
++ }
++ try {
++ sheet.insertRule(rule, sheet.cssRules.length);
++ }
++ catch (error) {
++ console.error('Error inserting rule from remote css', {
++ rule: rule,
++ error: error,
++ });
++ }
++}
+ function getCSSRules(styleSheets, options) {
+ return __awaiter(this, void 0, void 0, function () {
+- var ret, deferreds;
++ var ret, deferreds, fetchedRules;
+ return __generator(this, function (_a) {
+ ret = [];
+ deferreds = [];
++ fetchedRules = createDetachedSheet();
+ // First loop inlines imports
+ styleSheets.forEach(function (sheet) {
+ if ('cssRules' in sheet) {
+ try {
+ (0, util_1.toArray)(sheet.cssRules || []).forEach(function (item, index) {
+ if (item.type === CSSRule.IMPORT_RULE) {
+- var importIndex_1 = index + 1;
+ var url = item.href;
+- var deferred = fetchCSS(url)
++ var deferred = fetchCSS(url, options)
+ .then(function (metadata) { return embedFonts(metadata, options); })
+ .then(function (cssText) {
+ return parseCSS(cssText).forEach(function (rule) {
+- try {
+- sheet.insertRule(rule, rule.startsWith('@import')
+- ? (importIndex_1 += 1)
+- : sheet.cssRules.length);
+- }
+- catch (error) {
+- console.error('Error inserting rule from remote css', {
+- rule: rule,
+- error: error,
+- });
+- }
++ insertFetchedRule(fetchedRules, rule);
+ });
+ })
+ .catch(function (e) {
+@@ -173,13 +188,12 @@ function getCSSRules(styleSheets, options) {
+ });
+ }
+ catch (e) {
+- var inline_1 = styleSheets.find(function (a) { return a.href == null; }) || document.styleSheets[0];
+ if (sheet.href != null) {
+- deferreds.push(fetchCSS(sheet.href)
++ deferreds.push(fetchCSS(sheet.href, options)
+ .then(function (metadata) { return embedFonts(metadata, options); })
+ .then(function (cssText) {
+ return parseCSS(cssText).forEach(function (rule) {
+- inline_1.insertRule(rule, inline_1.cssRules.length);
++ insertFetchedRule(fetchedRules, rule);
+ });
+ })
+ .catch(function (err) {
+@@ -204,6 +218,9 @@ function getCSSRules(styleSheets, options) {
+ }
+ }
+ });
++ (0, util_1.toArray)(fetchedRules ? fetchedRules.cssRules : []).forEach(function (item) {
++ ret.push(item);
++ });
+ return ret;
+ })];
+ });
+@@ -243,7 +260,7 @@ function getUsedFonts(node) {
+ fonts.add(normalizeFontFamily(font));
+ });
+ Array.from(node.children).forEach(function (child) {
+- if (child instanceof HTMLElement) {
++ if ((0, util_1.isInstanceOfElement)(child, HTMLElement)) {
+ traverse(child);
+ }
+ });
+@@ -262,7 +279,7 @@ function getWebFontCSS(node, options) {
+ usedFonts = getUsedFonts(node);
+ return [4 /*yield*/, Promise.all(rules
+ .filter(function (rule) {
+- return usedFonts.has(normalizeFontFamily(rule.style.fontFamily));
++ return usedFonts.has(normalizeFontFamily(rule.style.getPropertyValue('font-family')));
+ })
+ .map(function (rule) {
+ var baseUrl = rule.parentStyleSheet
+diff --git a/lib/index.js b/lib/index.js
+index b8f1e8969373ea3b6a4217a884d129e471bbdf7c..252557f16f850650cdbcd041d89ab681fa36d49d 100644
+--- a/lib/index.js
++++ b/lib/index.js
+@@ -163,7 +163,7 @@ function toBlob(node, options) {
+ case 0: return [4 /*yield*/, toCanvas(node, options)];
+ case 1:
+ canvas = _a.sent();
+- return [4 /*yield*/, (0, util_1.canvasToBlob)(canvas)];
++ return [4 /*yield*/, (0, util_1.canvasToBlob)(canvas, options)];
+ case 2:
+ blob = _a.sent();
+ return [2 /*return*/, blob];
diff --git a/lib/util.js b/lib/util.js
-index 6a6ae9c8bd15b276d46773d853c2182aaba8326e..8e6a8aaf6e97a51c05f99aa698deb262a875f8f5 100644
+index 6a6ae9c8bd15b276d46773d853c2182aaba8326e..55968896a06e928da2a03f7f2af176ab2352c81b 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -50,16 +50,17 @@ function resolveUrl(url, baseUrl) {
@@ -60,3 +480,14 @@ index 6a6ae9c8bd15b276d46773d853c2182aaba8326e..8e6a8aaf6e97a51c05f99aa698deb262
}
exports.resolveUrl = resolveUrl;
exports.uuid = (function () {
+@@ -202,7 +203,9 @@ function createImage(url) {
+ return new Promise(function (resolve, reject) {
+ var img = new Image();
+ img.onload = function () {
+- img.decode().then(function () {
++ img.decode()
++ .catch(function () { return undefined; })
++ .then(function () {
+ requestAnimationFrame(function () { return resolve(img); });
+ });
+ };
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 63e91196fb98..00ff0e124faf 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -199,7 +199,7 @@ patchedDependencies:
hash: d95e6638894935a75bd93b60b5243cb825892a1eedcc4c9a125a3e7dce8b64f0
path: patches/[email protected]
- hash: c51d4e8d9f649ee8a8e61577347ca1e4a9da029e91a073a91aae08ebf783d5d2
+ hash: f0a5786708aab63eb75c89a2c8de10a8da63fce02a5d9ab588fbe684cab8951e
path: patches/[email protected]
hash: b78c8d985264045675ad1405ea3773eb504f97e0725f24ed35bd348f66d41811
@@ -1111,7 +1111,7 @@ importers:
version: 1.5.15
html-to-image:
specifier: ^1.11.13
- version: 1.11.13(patch_hash=c51d4e8d9f649ee8a8e61577347ca1e4a9da029e91a073a91aae08ebf783d5d2)
+ version: 1.11.13(patch_hash=f0a5786708aab63eb75c89a2c8de10a8da63fce02a5d9ab588fbe684cab8951e)
husky:
specifier: 'catalog:'
version: 7.0.4
@@ -37870,7 +37870,7 @@ snapshots:
- [email protected](patch_hash=c51d4e8d9f649ee8a8e61577347ca1e4a9da029e91a073a91aae08ebf783d5d2): {}
+ [email protected](patch_hash=f0a5786708aab63eb75c89a2c8de10a8da63fce02a5d9ab588fbe684cab8951e): {}