Source code

Revision control

Other Tools

1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
* You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5
"use strict";
6
7
var EXPORTED_SYMBOLS = ["HeadlessShell"];
8
9
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
10
const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm");
11
12
// Refrences to the progress listeners to keep them from being gc'ed
13
// before they are called.
14
const progressListeners = new Map();
15
16
function loadContentWindow(webNavigation, url, principal) {
17
let uri;
18
try {
19
uri = Services.io.newURI(url);
20
} catch (e) {
21
let msg = `Invalid URL passed to loadContentWindow(): ${url}`;
22
Cu.reportError(msg);
23
return Promise.reject(new Error(msg));
24
}
25
return new Promise((resolve, reject) => {
26
let loadURIOptions = {
27
triggeringPrincipal: principal,
28
};
29
webNavigation.loadURI(uri.spec, loadURIOptions);
30
let docShell = webNavigation.QueryInterface(Ci.nsIInterfaceRequestor)
31
.getInterface(Ci.nsIDocShell);
32
let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
33
.getInterface(Ci.nsIWebProgress);
34
let progressListener = {
35
onLocationChange(progress, request, location, flags) {
36
// Ignore inner-frame events
37
if (progress != webProgress) {
38
return;
39
}
40
// Ignore events that don't change the document
41
if (flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT) {
42
return;
43
}
44
// Ignore the initial about:blank, unless about:blank is requested
45
if (location.spec == "about:blank" && uri.spec != "about:blank") {
46
return;
47
}
48
let contentWindow = docShell.domWindow;
49
progressListeners.delete(progressListener);
50
webProgress.removeProgressListener(progressListener);
51
contentWindow.addEventListener("load", (event) => {
52
resolve(contentWindow);
53
}, { once: true });
54
},
55
QueryInterface: ChromeUtils.generateQI(["nsIWebProgressListener",
56
"nsISupportsWeakReference"]),
57
};
58
progressListeners.set(progressListener, progressListener);
59
webProgress.addProgressListener(progressListener,
60
Ci.nsIWebProgress.NOTIFY_LOCATION);
61
});
62
}
63
64
async function takeScreenshot(fullWidth, fullHeight, contentWidth, contentHeight, path, url) {
65
try {
66
var windowlessBrowser = Services.appShell.createWindowlessBrowser(false);
67
// nsIWindowlessBrowser inherits from nsIWebNavigation.
68
let contentWindow = await loadContentWindow(windowlessBrowser, url, Services.scriptSecurityManager.getSystemPrincipal());
69
contentWindow.resizeTo(contentWidth, contentHeight);
70
71
let canvas = contentWindow.document.createElementNS("http://www.w3.org/1999/xhtml", "html:canvas");
72
let context = canvas.getContext("2d");
73
let width = fullWidth ? contentWindow.innerWidth + contentWindow.scrollMaxX - contentWindow.scrollMinX
74
: contentWindow.innerWidth;
75
let height = fullHeight ? contentWindow.innerHeight + contentWindow.scrollMaxY - contentWindow.scrollMinY
76
: contentWindow.innerHeight;
77
canvas.width = width;
78
canvas.height = height;
79
context.drawWindow(contentWindow, 0, 0, width, height, "rgb(255, 255, 255)");
80
81
function getBlob() {
82
return new Promise(resolve => canvas.toBlob(resolve));
83
}
84
85
function readBlob(blob) {
86
return new Promise(resolve => {
87
let reader = new FileReader();
88
reader.onloadend = () => resolve(reader);
89
reader.readAsArrayBuffer(blob);
90
});
91
}
92
93
let blob = await getBlob();
94
let reader = await readBlob(blob);
95
await OS.File.writeAtomic(path, new Uint8Array(reader.result), {flush: true});
96
dump("Screenshot saved to: " + path + "\n");
97
} catch (e) {
98
dump("Failure taking screenshot: " + e + "\n");
99
} finally {
100
if (windowlessBrowser) {
101
windowlessBrowser.close();
102
}
103
}
104
}
105
106
let HeadlessShell = {
107
async handleCmdLineArgs(cmdLine, URLlist) {
108
try {
109
// Don't quit even though we don't create a window
110
Services.startup.enterLastWindowClosingSurvivalArea();
111
112
// Default options
113
let fullWidth = true;
114
let fullHeight = true;
115
// Most common screen resolution of Firefox users
116
let contentWidth = 1366;
117
let contentHeight = 768;
118
119
// Parse `window-size`
120
try {
121
var dimensionsStr = cmdLine.handleFlagWithParam("window-size", true);
122
} catch (e) {
123
dump("expected format: --window-size width[,height]\n");
124
return;
125
}
126
if (dimensionsStr) {
127
let success;
128
let dimensions = dimensionsStr.split(",", 2);
129
if (dimensions.length == 1) {
130
success = dimensions[0] > 0;
131
if (success) {
132
fullWidth = false;
133
fullHeight = true;
134
contentWidth = dimensions[0];
135
}
136
} else {
137
success = dimensions[0] > 0 && dimensions[1] > 0;
138
if (success) {
139
fullWidth = false;
140
fullHeight = false;
141
contentWidth = dimensions[0];
142
contentHeight = dimensions[1];
143
}
144
}
145
146
if (!success) {
147
dump("expected format: --window-size width[,height]\n");
148
return;
149
}
150
}
151
152
// Only command line argument left should be `screenshot`
153
// There could still be URLs however
154
try {
155
var path = cmdLine.handleFlagWithParam("screenshot", true);
156
if (!cmdLine.length && !URLlist.length) {
157
URLlist.push(path); // Assume the user wanted to specify a URL
158
path = OS.Path.join(cmdLine.workingDirectory.path, "screenshot.png");
159
}
160
} catch (e) {
161
path = OS.Path.join(cmdLine.workingDirectory.path, "screenshot.png");
162
cmdLine.handleFlag("screenshot", true); // Remove `screenshot`
163
}
164
165
for (let i = 0; i < cmdLine.length; ++i) {
166
URLlist.push(cmdLine.getArgument(i)); // Assume that all remaining arguments are URLs
167
}
168
169
if (URLlist.length == 1) {
170
await takeScreenshot(fullWidth, fullHeight, contentWidth, contentHeight, path, URLlist[0]);
171
} else {
172
dump("expected exactly one URL when using `screenshot`\n");
173
}
174
} finally {
175
Services.startup.exitLastWindowClosingSurvivalArea();
176
Services.startup.quit(Ci.nsIAppStartup.eForceQuit);
177
}
178
},
179
};