-
Notifications
You must be signed in to change notification settings - Fork 7
/
browserLauncher.js
82 lines (71 loc) · 2.6 KB
/
browserLauncher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var Promise = require('rsvp').Promise;
var readline = require('readline');
var chromiumPaths = [
// Mac Canary
path.join('/Applications', 'Google Chrome Canary.app', 'Contents', 'MacOS', 'Google Chrome Canary')
];
function ask(question, opts) {
return new Promise(function(resolve, reject) {
opts = opts || {};
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(question + ' ', function(answer) {
rl.close();
if (opts.process) {
answer = opts.process(answer);
}
if (opts.validate && !opts.validate(answer)) {
console.error(opts.errorMsg || "Invalid answer, try again");
return ask(question, opts);
}
resolve(answer);
});
});
}
module.exports = function browserLauncher(chromiumPath, proxyPort) {
return Promise.resolve()
.then(function() {
if (chromiumPath) {
return chromiumPath;
}
for (var i = 0; i < chromiumPaths.length; i++) {
if (fs.existsSync(chromiumPaths[i])) {
return chromiumPaths[i];
}
}
return ask("Enter path to Chrome:", {
validate: function(chromiumPath) {
return fs.existsSync(chromiumPath);
},
errorMsg: "Cannot find Chromium"
});
})
.then(function(chromiumPath) {
var process = spawn(chromiumPath, [
"--proxy-server=http=localhost:" + Number(proxyPort),
"--load-extension=" + path.join(__dirname, "extension")
]);
return new Promise(function(resolve, reject) {
process.on('error', function(err) {
if (err.code == "ENOENT") {
reject(Error("No browser at " + chromiumPath));
} else {
reject(err);
}
});
process.on('exit', function(code) {
if (code) {
reject(Error("Cannot start \""+ chromiumPath +"\", ensure it isn't already running, and try again."));
}
});
setTimeout(function() {
resolve(process);
}, 3000); // assuming everything's ok after a second. Yeah, I know.
});
});
};