Skip to content

Build your personal knowledge base with Trilium Notes

feat(clipper): capture a full page in Firefox without scrolling through it

Elian Doran6cfc48b9f700
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html
index 539462fd67..511be550a8 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html
@@ -115,10 +115,13 @@
once, at the top of the image, and headings that stick while scrolling
appear where they are in the page. Other elements that stay in place while
scrolling (such as cookie banners and chat buttons) are left out, while
- a background that fills the whole window repeats on every screen. A long
- page is saved as several images, one below the other in the note. A page
- longer than 100 screens is cut off there, and the message after saving
- says so. Screenshots keep their full height in Trilium: <em>Resize image</em> (under <em>Automatically compress images</em> in
+ a background that fills the whole window repeats on every screen. In Firefox,
+ the page is captured without scrolling through it, which is faster: such
+ a background then appears only at the top, and images that the page loads
+ only once they are scrolled into view can be missing. A long page is saved
+ as several images, one below the other in the note. A page longer than
+ 100 screens is cut off there, and the message after saving says so. Screenshots
+ keep their full height in Trilium: <em>Resize image</em> (under <em>Automatically compress images</em> in
Options → Media) limits only their width.</p>
</li>
<li>
diff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.ts
index 058faa265f..da6ab748fb 100644
--- a/apps/web-clipper/entrypoints/background/index.spec.ts
+++ b/apps/web-clipper/entrypoints/background/index.spec.ts
@@ -803,6 +803,38 @@ describe("background", () => {
expect(backgroundStitcher.add).toHaveBeenCalledWith({ dataUrl: PNG, y: 0 });
expect(lastPayload()).toMatchObject({ images: [ { dataUrl: CROPPED_PNG } ] });
});
+
+ it("captures the page by area with Firefox's captureTab, without scrolling through it", async () => {
+ vi.stubGlobal("__MANIFEST_VERSION__", 2);
+ backgroundStitcher.finish.mockReturnValue([ CROPPED_PNG ]);
+ const captureTab = vi.fn(async () => PNG);
+ Object.assign(fakeBrowser.tabs, { captureTab });
+ try {
+ simulatePage({ startY: 300, viewportHeight: 500, viewportWidth: 800, pageHeight: 12000, devicePixelRatio: 2 });
+ await run(sendRuntimeMessage({ name: "save-full-page-screenshot" }));
+
+ expect(pageSteps()).toEqual([ undefined, 0, "first", 0, "restore", 300 ]);
+ // 4,096 CSS px is 8,192 device pixels; each area reaches a pixel into the next.
+ expect(captureTab.mock.calls).toEqual([ 0, 4096, 8192 ].map((y) => [ 7, {
+ format: "png",
+ rect: { x: 0, y, width: 800, height: Math.min(4097, 12000 - y) }
+ } ]));
+ expect(backgroundStitcher.created).toHaveBeenCalledWith({ pageHeight: 12000, devicePixelRatio: 2 });
+ expect(backgroundStitcher.add.mock.calls).toEqual([ 0, 4096, 8192 ].map((y) => [ { dataUrl: PNG, y } ]));
+ expect(captureVisibleTab).not.toHaveBeenCalled();
+ expect(await lastToast()).toMatchObject({ message: "Screenshot has been saved to Trilium." });
+
+ // A page loaded before the extension was updated does not give its width.
+ vi.useFakeTimers({ toFake: [ "setTimeout", "Date" ] });
+ captureTab.mockClear();
+ simulatePage({ viewportHeight: 500, pageHeight: 500 });
+ await run(sendRuntimeMessage({ name: "save-full-page-screenshot" }));
+ expect(captureTab).not.toHaveBeenCalled();
+ expect(captureVisibleTab).toHaveBeenCalledOnce();
+ } finally {
+ Reflect.deleteProperty(fakeBrowser.tabs, "captureTab");
+ }
+ });
});
describe("context menu", () => {
@@ -1182,9 +1214,11 @@ async function lastToast() {
* `scrollLimit`, starting at `startY`. `prepared` is the size it has once its scrollbars are
* hidden.
*/
-function simulatePage({ startY = 0, viewportHeight, pageHeight, scrollLimit = pageHeight, devicePixelRatio = 1, prepared }: {
- startY?: number, viewportHeight: number, pageHeight: number, scrollLimit?: number, devicePixelRatio?: number,
- prepared?: { viewportHeight: number, pageHeight: number }
+function simulatePage({
+ startY = 0, viewportHeight, viewportWidth, pageHeight, scrollLimit = pageHeight, devicePixelRatio = 1, prepared
+}: {
+ startY?: number, viewportHeight: number, viewportWidth?: number, pageHeight: number, scrollLimit?: number,
+ devicePixelRatio?: number, prepared?: { viewportHeight: number, pageHeight: number }
}) {
let scrollY = startY;
let size = { viewportHeight, pageHeight, scrollLimit };
@@ -1197,7 +1231,10 @@ function simulatePage({ startY = 0, viewportHeight, pageHeight, scrollLimit = pa
if (y !== undefined) {
scrollY = Math.max(0, Math.min(y, size.scrollLimit - size.viewportHeight));
}
- return { scrollX: 0, scrollY, viewportHeight: size.viewportHeight, pageHeight: size.pageHeight, devicePixelRatio };
+ return {
+ scrollX: 0, scrollY, viewportHeight: size.viewportHeight, pageHeight: size.pageHeight, devicePixelRatio,
+ ...(viewportWidth && { viewportWidth })
+ };
};
}
diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.ts
index 9aee689235..53e576114e 100644
--- a/apps/web-clipper/entrypoints/background/index.ts
+++ b/apps/web-clipper/entrypoints/background/index.ts
@@ -1,5 +1,5 @@
import {
- type ScreenshotSlice, ScreenshotStitcher, type StitchMessage, type StitchRequest
+ MAX_PART_HEIGHT, type ScreenshotSlice, ScreenshotStitcher, type StitchMessage, type StitchRequest
} from "@/screenshot";
import { extractPage, isPdfTab, randomString, type Rect, type SaveOutcome, type Saved } from "@/utils";
@@ -36,10 +36,19 @@ type ScrollPosition = {
scrollX: number;
scrollY: number;
viewportHeight: number;
+ /** Not given by a content script from an earlier version of the extension. */
+ viewportWidth?: number;
pageHeight: number;
devicePixelRatio: number;
};
+/**
+ * Firefox's `tabs.captureTab()`, which captures any area of the page, in CSS pixels from its top,
+ * at the page's pixel ratio. Chrome has no such function.
+ */
+type CaptureTab = (tabId: number, options: { format: "png", rect: CaptureRect }) => Promise<string>;
+type CaptureRect = { x: number, y: number, width: number, height: number };
+
/** Draws the captures of a full-page screenshot into images, wherever the canvas is. */
interface Stitcher {
add(slice: ScreenshotSlice): Promise<void>;
@@ -195,28 +204,12 @@ export default defineBackground(() => {
const height = Math.min(page.pageHeight, MAX_SCREENSHOT_CAPTURES * page.viewportHeight);
const stitcher = await createStitcher({ pageHeight: height, devicePixelRatio: page.devicePixelRatio });
- let position = page;
- let lastCaptureAt = 0;
- for (;;) {
- await delay(Math.max(SCROLL_SETTLE_MS, lastCaptureAt + CAPTURE_INTERVAL_MS - Date.now()));
- const tab = await browser.tabs.get(tabId);
- if (!tab.active) {
- throw new Error("The screenshot was stopped because another tab was opened.");
- }
-
- lastCaptureAt = Date.now();
- const dataUrl = await browser.tabs.captureVisibleTab(windowId, { format: "png" });
- await stitcher.add({ dataUrl, y: position.scrollY });
- if (position === page) {
- await setFloatingElements(tabId, "rest");
- }
-
- const y = position.scrollY + page.viewportHeight;
- if (y >= height) break;
- const next = await scrollTab(tabId, start.scrollX, y);
- // The page stopped scrolling short of the height it reported.
- if (next.scrollY <= position.scrollY) break;
- position = next;
+ const { captureTab } = browser.tabs as typeof browser.tabs & { captureTab?: CaptureTab };
+ if (captureTab && page.viewportWidth) {
+ const captureRect = (rect: CaptureRect) => captureTab.call(browser.tabs, tabId, { format: "png", rect });
+ await captureByArea(tabId, { ...page, viewportWidth: page.viewportWidth }, height, stitcher, captureRect);
+ } else {
+ await captureByScrolling(tabId, windowId, page, height, stitcher);
}
return { parts: await stitcher.finish(), cutOff: height < page.pageHeight };
@@ -226,6 +219,62 @@ export default defineBackground(() => {
}
}
+ /** Scrolls through the page a viewport at a time, capturing each, as often as Chrome allows. */
+ async function captureByScrolling(
+ tabId: number, windowId: number, page: ScrollPosition, height: number, stitcher: Stitcher
+ ) {
+ let position = page;
+ let lastCaptureAt = 0;
+ for (;;) {
+ await delay(Math.max(SCROLL_SETTLE_MS, lastCaptureAt + CAPTURE_INTERVAL_MS - Date.now()));
+ await assertTabActive(tabId);
+
+ lastCaptureAt = Date.now();
+ const dataUrl = await browser.tabs.captureVisibleTab(windowId, { format: "png" });
+ await stitcher.add({ dataUrl, y: position.scrollY });
+ if (position === page) {
+ await setFloatingElements(tabId, "rest");
+ }
+
+ const y = position.scrollY + page.viewportHeight;
+ if (y >= height) break;
+ const next = await scrollTab(tabId, page.scrollX, y);
+ // The page stopped scrolling short of the height it reported.
+ if (next.scrollY <= position.scrollY) break;
+ position = next;
+ }
+ }
+
+ /**
+ * Captures the page from the top with Firefox's `tabs.captureTab()`, an area of up to one image
+ * at a time, without scrolling. A fixed header is drawn where it is, at the top. Each area reaches
+ * a CSS pixel into the next, so a fractional pixel ratio leaves no gap between them.
+ */
+ async function captureByArea(
+ tabId: number,
+ page: ScrollPosition & { viewportWidth: number },
+ height: number,
+ stitcher: Stitcher,
+ captureRect: (rect: CaptureRect) => Promise<string>
+ ) {
+ const step = Math.floor(MAX_PART_HEIGHT / page.devicePixelRatio);
+ await delay(SCROLL_SETTLE_MS);
+ for (let y = 0; y < height; y += step) {
+ await assertTabActive(tabId);
+ const dataUrl = await captureRect({
+ x: page.scrollX, y, width: page.viewportWidth, height: Math.min(step + 1, height - y)
+ });
+ await stitcher.add({ dataUrl, y });
+ }
+ }
+
+ async function assertTabActive(tabId: number) {
+ const tab = await browser.tabs.get(tabId);
+ if (!tab.active) {
+ throw new Error("The screenshot was stopped because another tab was opened.");
+ }
+ }
+
async function saveFullPageScreenshot(pageUrl: string | null | undefined) {
const { parts, cutOff } = await takeFullPageScreenshot();
return await saveScreenshot(parts, pageUrl, cutOff
diff --git a/apps/web-clipper/entrypoints/content/index.spec.ts b/apps/web-clipper/entrypoints/content/index.spec.ts
index 0cbb7d86b5..ad3c79aa7c 100644
--- a/apps/web-clipper/entrypoints/content/index.spec.ts
+++ b/apps/web-clipper/entrypoints/content/index.spec.ts
@@ -251,6 +251,7 @@ describe("content script", () => {
scrollX: window.scrollX,
scrollY: 240,
viewportHeight: window.innerHeight,
+ viewportWidth: window.innerWidth,
pageHeight: 3000,
devicePixelRatio: window.devicePixelRatio
};
diff --git a/apps/web-clipper/entrypoints/content/index.ts b/apps/web-clipper/entrypoints/content/index.ts
index f41e1c9092..9adf2ada3e 100644
--- a/apps/web-clipper/entrypoints/content/index.ts
+++ b/apps/web-clipper/entrypoints/content/index.ts
@@ -224,6 +224,7 @@ export default defineContentScript({
scrollX: window.scrollX,
scrollY: window.scrollY,
viewportHeight: window.innerHeight,
+ viewportWidth: window.innerWidth,
pageHeight: document.documentElement.scrollHeight,
devicePixelRatio: window.devicePixelRatio
};
diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
index 43deb21d71..8639683c6b 100644
--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
@@ -44,7 +44,7 @@ Clicking the extension's button in the browser toolbar opens its popup:
The popup opens on the selection if there is one, otherwise on _Page_, showing the article, or the whole page when the page has no article. On a PDF, it opens on _PDF_. On a page that shows nothing to save, it opens on _Bookmark_ and says so. The keyboard shortcuts and the context menu still save right away, without a preview: saving the whole page that way saves the article, the whole page when the page has no article, or the PDF when the tab shows one.
* Pages the extension cannot access (the browser's own pages, the extension stores, and pages that were open before the extension was installed until they are reloaded) cannot be saved or captured, so the popup says so in place of the preview, and only _Tabs_ remains available there.
* Below the preview, a row of buttons offers the other actions: _Crop_ (a screenshot of an area you select), _Screenshot_ (of the visible part of the page), _Full page_ (a screenshot of the whole page) and _Tabs_ (saves the links of every tab in the current window as a list of <a class="reference-link" href="../Note%20Types/Text/Link%20Previews.md">Link Previews</a>, or of plain links when _Autogenerate link previews_ is turned off). Hovering over a button shows its full name and, if it has one, its keyboard shortcut.
-* _Full page_ scrolls through the page, takes a screenshot of each part and joins them into one image, then scrolls back to where the page was. The scrollbars are hidden while it does, so they do not appear in the image. Stay on the tab until it is saved: switching to another tab stops the screenshot. A header that stays at the top of the window appears once, at the top of the image, and headings that stick while scrolling appear where they are in the page. Other elements that stay in place while scrolling (such as cookie banners and chat buttons) are left out, while a background that fills the whole window repeats on every screen. A long page is saved as several images, one below the other in the note. A page longer than 100 screens is cut off there, and the message after saving says so. Screenshots keep their full height in Trilium: _Resize image_ (under _Automatically compress images_ in Options → Media) limits only their width.
+* _Full page_ scrolls through the page, takes a screenshot of each part and joins them into one image, then scrolls back to where the page was. The scrollbars are hidden while it does, so they do not appear in the image. Stay on the tab until it is saved: switching to another tab stops the screenshot. A header that stays at the top of the window appears once, at the top of the image, and headings that stick while scrolling appear where they are in the page. Other elements that stay in place while scrolling (such as cookie banners and chat buttons) are left out, while a background that fills the whole window repeats on every screen. In Firefox, the page is captured without scrolling through it, which is faster: such a background then appears only at the top, and images that the page loads only once they are scrolled into view can be missing. A long page is saved as several images, one below the other in the note. A page longer than 100 screens is cut off there, and the message after saving says so. Screenshots keep their full height in Trilium: _Resize image_ (under _Automatically compress images_ in Options → Media) limits only their width.
* The popup stays open while Trilium saves, which can take a few seconds for a long page or a large PDF, and the other actions wait until it is done. The bar at the top of the popup then says, in green, that the clipping was saved (in place of the notice that the page was already clipped), with _Open note_ to open it in Trilium (and, after _Tabs_, _Close saved tabs_), or, in red, why it could not be saved. The same clipping cannot be saved twice by accident: the save button stays disabled until another mode is chosen. _Crop_ is the exception: the popup closes so that an area of the page can be selected, and the notification on the page reports the outcome.
* If the current page was already clipped, a notice at the top offers to open the note in Trilium.
* If Trilium cannot be found, the popup explains why instead of showing the actions, with buttons to look for Trilium again and to open the options.