使用 SDK,您可以执行以下操作:
const { window: { document } } = require('sdk/addon/window');
const { getTabContentWindow, getActiveTab } = require('sdk/tabs/utils');
const { getMostRecentBrowserWindow } = require('sdk/window/utils');
const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
document.documentElement.appendChild(canvas);
function captureTab(tab=getActiveTab(getMostRecentBrowserWindow())) {
let contentWindow = getTabContentWindow(tab);
let w = contentWindow.innerWidth;
let h = contentWindow.innerHeight;
let x = contentWindow.scrollX;
let y = contentWindow.scrollY;
canvas.width = w;
canvas.height = h;
let ctx = canvas.getContext('2d');
ctx.drawWindow(contentWindow, x, y, w, h, '#000');
return canvas.toDataURL();
}
这应该只占用可见区域。默认情况下,它会抓取活动选项卡,但您可以传递任何其他选项卡——因为它被设计为低级 API,它需要一个原生选项卡,而不是 SDK 选项卡。
您可以放入一个模块并仅导出 captureTab 函数。
编辑:e10s 版本
正如 Ian Bicking 在评论中指出的那样,上面的代码目前与带有 e10s 的 Firefox 不兼容。解决此问题的一种简单方法是在我们要捕获屏幕截图的同一文档和内容进程中创建一个临时画布:
const { getTabContentWindow, getActiveTab } = require('sdk/tabs/utils');
const { getMostRecentBrowserWindow } = require('sdk/window/utils');
function captureTab(tab=getActiveTab(getMostRecentBrowserWindow())) {
let contentWindow = getTabContentWindow(tab);
let { document } = contentWindow;
let w = contentWindow.innerWidth;
let h = contentWindow.innerHeight;
let x = contentWindow.scrollX;
let y = contentWindow.scrollY;
let canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
canvas.width = w;
canvas.height = h;
let ctx = canvas.getContext('2d');
ctx.drawWindow(contentWindow, x, y, w, h, '#000');
let dataURL = canvas.toDataURL();
canvas = null;
return dataURL;
}
这适用于 e10s 和 no-e10s FF 版本;与上一个相比的缺点是每次我们想要截屏时都会创建一个画布,但我认为是可以接受的。