({
code,
scriptingApi,
tabId,
timeoutMs = DEFAULT_EVAL_TIMEOUT_MS,
}: {
readonly code: string;
readonly scriptingApi: BrowserScriptingApi;
readonly tabId: number;
readonly timeoutMs?: number;
})
| 768 | dataUrl, |
| 769 | devicePixelRatio: 1, |
| 770 | height: dimensions?.height ?? 0, |
| 771 | mediaType: 'image/png', |
| 772 | width: dimensions?.width ?? 0, |
| 773 | } satisfies ViewportScreenshot, |
| 774 | }; |
| 775 | }; |
| 776 | |
| 777 | export const getViewportScreenshotWithTabsApi = async ({ |
| 778 | tabId, |
| 779 | tabsApi, |
| 780 | }: { |
| 781 | readonly tabId: number; |
| 782 | readonly tabsApi: BrowserTabsApi; |
| 783 | }): Promise<EvalTabResult> => { |
| 784 | const captureTab = tabsApi.captureTab?.bind(tabsApi); |
| 785 | |
| 786 | // Firefox renders any tab on its own, so the user's foreground tab is never switched away (D9). |
| 787 | if (captureTab !== undefined) { |
| 788 | try { |
| 789 | return viewportScreenshotOf(await captureTab(tabId, { format: 'png', scale: 1 })); |
| 790 | } catch (error) { |
| 791 | return { |
| 792 | error: error instanceof Error ? error.message : 'The tab could not be captured.', |
| 793 | ok: false, |
| 794 | }; |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | const captureVisibleTab = tabsApi.captureVisibleTab?.bind(tabsApi); |
| 799 | const getTab = tabsApi.get?.bind(tabsApi); |
| 800 | const updateTab = tabsApi.update?.bind(tabsApi); |
| 801 | const queryTabs = tabsApi.query.bind(tabsApi); |
| 802 | |
| 803 | if (captureVisibleTab === undefined || getTab === undefined || updateTab === undefined) { |
| 804 | return { error: 'Viewport screenshot API is unavailable.', ok: false }; |
| 805 | } |
| 806 | |
| 807 | return runScreenshotCaptureExclusively(async () => { |
| 808 | const { windowId } = await getTab(tabId); |
| 809 | const activeTabQuery = |
| 810 | windowId === undefined ? { active: true, currentWindow: true } : { active: true, windowId }; |
| 811 | const [previousActiveTab] = await queryTabs(activeTabQuery); |
| 812 | const previousActiveTabId = getTabId(previousActiveTab); |
| 813 | |
| 814 | try { |
| 815 | await updateTab(tabId, { active: true }); |
| 816 | const [activeTab] = await queryTabs(activeTabQuery); |
| 817 | |
| 818 | // A manual tab switch can land between activation and capture; refuse rather than capture and upload a different tab's contents. |
| 819 | if (getTabId(activeTab) !== tabId) { |
| 820 | return { error: 'The selected tab was not active at capture time.', ok: false }; |
no test coverage detected