-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
230 lines (202 loc) · 6.05 KB
/
index.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
const CDP = require('chrome-remote-interface');
const fs = require('fs');
const events = require('events');
class ChromePageObject {
constructor({ targetId } = {}) {
this.targetId = targetId;
events.EventEmitter.defaultMaxListeners = Infinity;
}
getCDP() {
return new Promise((resolve) => {
if (this._client) {
resolve(this._client);
return;
}
const startRequest = Date.now();
let backoffStartupTime = 25;
const maxStartupTime = 60000;
const initCDP = () => {
CDP(async (client) => {
this._client = client;
// If we have a targetId, connect to that.
if (this.targetId) {
const { Target } = client;
try {
await Target.attachToTarget({ targetId: this.targetId });
} catch(e) {
console.log('Could not attach to target', this.targetId, e);
}
}
resolve(client);
}).on('error', (err) => {
if (Date.now() - startRequest > maxStartupTime) {
console.error("CDP Error: " + err.stack);
} else {
backoffStartupTime *= 2;
setTimeout(initCDP, backoffStartupTime);
}
});
};
setTimeout(initCDP, backoffStartupTime);
})
}
open(url, cb) {
this.getCDP().then(async (client) => {
const { Page, Emulation, Runtime, Security, Target } = client;
const defaultViewportHeight = 300;
const defaultViewportWidth = 400;
const deviceMetrics = {
width: defaultViewportWidth,
height: defaultViewportHeight,
deviceScaleFactor: 0,
mobile: false,
fitWindow: true
};
try {
Security.certificateError((res) => {
cb(null, 'fail');
})
await Target.setDiscoverTargets({ discover: true });
Target.targetCreated(async ({ targetInfo }) => {
if (targetInfo.type === 'page') {
const { targetId } = targetInfo;
// TODO: Handle the rest of the phantom childPage contract used in ghost.
const subPageObj = new ChromePageObject({ targetId });
const targetLocation = subPageObj.evaluate(() => window.location.toString(), (err, targetLocation) => {
this.onPageCreated(subPageObj);
subPageObj.onUrlChanged(targetLocation);
})
}
})
await Page.enable();
await Security.enable();
await Emulation.setDeviceMetricsOverride(deviceMetrics);
await Page.navigate({url: url});
await Page.loadEventFired(() => {
cb(null, url);
});
} catch (err) {
console.error(err.stack);
cb('fail', null);
}
});
}
async render(filePath) {
this.getCDP().then(async (client) => {
const { Page } = client;
try {
const { data } = await Page.captureScreenshot();
fs.writeFileSync(filePath, Buffer.from(data, 'base64'));
} catch (err) {
console.error(err);
}
});
}
evaluate(fn, ...args) {
this.getCDP().then(async (client) => {
const { Page, Runtime } = client;
try {
const cb = args.pop();
let executor = (stringyFunc, args) => {
let invoke = new Function(
"return " + stringyFunc
)();
return invoke.apply(null, args)
}
let executorString = `(${executor})(${fn.toString()}, ${JSON.stringify(args)})`
await Runtime.enable();
const { result } = await Runtime.evaluate({expression: executorString, returnByValue: true});
const value = result.value;
cb (null, value);
} catch (err) {
console.log(err.stack)
const cb = args.pop();
cb(err, null);
console.error(err);
}
});
}
async goForward() {
this.getCDP().then(async (client) => {
const { Page } = client;
try {
await Page.enable();
let {currentIndex, entries} = await Page.getNavigationHistory()
if (currentIndex === entries.length-1) {
return;
} else {
await Page.navigateToHistoryEntry({ entryId: entries[currentIndex+1].id });
}
} catch (err) {
console.error(err);
}
});
}
async goBack() {
this.getCDP().then(async (client) => {
const { Page } = client;
try {
await Page.enable();
let {currentIndex, entries} = await Page.getNavigationHistory();
if (currentIndex === 0) {
return;
} else {
await Page.navigateToHistoryEntry({ entryId: entries[currentIndex-1].id });
}
} catch (err) {
console.error(err);
}
});
}
async injectJs(scriptPath) {
const js = fs.readFileSync(scriptPath, {encoding: 'utf8'}).trim();
// TODO: Allow this to be async.
// this.getCDP().then(async (client) => {
const { Page, Runtime } = this._client;
try {
let expression = `(()=>{${js}})()`
const result = await Runtime.evaluate({ expression: expression });
} catch (err) {
console.error(err);
}
// });
}
close() {
this.getCDP().then(async (client) => {
if (this.targetId) {
const { Target } = client;
Target.detachFromTarget({ targetId: this.targetId });
}
await client.close();
});
}
set(param, options) {
this.getCDP().then(async (client) => {
if (param === 'viewportSize') {
const { width, height } = options;
const { Emulation } = client;
const deviceMetrics = {
width: width,
height: height,
deviceScaleFactor: 0,
mobile: false,
fitWindow: true
};
Emulation.setDeviceMetricsOverride(deviceMetrics);
}
})
}
}
ChromePageObject.create = (options, callback) => {
const pageObj = new ChromePageObject();
callback(null, {
createPage: (pageCb) => {
pageCb(null, pageObj)
},
exit: () => {
pageObj.close();
}
})
}
ChromePageObject.path = __dirname + '/binary'
module.exports = ChromePageObject;