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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// CDPClient
//
class CDPClient {
constructor() {
this._requestId = 0;
this._sessions = new Map();
}
nextRequestId() {
return ++this._requestId;
}
addSession(session) {
this._sessions.set(session.sessionId(), session);
}
getSession(sessionId) {
this._sessions.get(sessionId);
}
async dispatchMessage(message) {
const messageObject = JSON.parse(message);
const session = this._sessions.get(messageObject.sessionId || '');
if (session) {
session.dispatchMessage(messageObject);
}
}
reportError(message, error) {
if (error) {
console.error(`${message}: ${error}\n${error.stack}`);
} else {
console.error(message);
}
}
}
const cdpClient = new CDPClient();
//
// CDPSession
//
class CDPSession {
constructor(sessionId) {
this._sessionId = sessionId || '';
this._parentSessionId = null;
this._dispatchTable = new Map();
this._eventHandlers = new Map();
this._protocol = this._getProtocol();
cdpClient.addSession(this);
}
sessionId() {
return this._sessionId;
}
protocol() {
return this._protocol;
}
createSession(sessionId) {
const session = new CDPSession(sessionId);
session._parentSessionId = this._sessionId;
return session;
}
async sendCommand(method, params) {
const requestId = cdpClient.nextRequestId();
const messageObject = {'id': requestId, 'method': method, 'params': params};
if (this._sessionId) {
messageObject.sessionId = this._sessionId;
}
sendDevToolsMessage(JSON.stringify(messageObject));
return new Promise(f => this._dispatchTable.set(requestId, f));
}
async dispatchMessage(message) {
try {
const messageId = message.id;
if (typeof messageId === 'number') {
const handler = this._dispatchTable.get(messageId);
if (handler) {
this._dispatchTable.delete(messageId);
handler(message);
} else {
cdpClient.reportError(`Unexpected result id ${messageId}`);
}
} else {
const eventName = message.method;
for (const handler of (this._eventHandlers.get(eventName) || [])) {
handler(message);
}
}
} catch (e) {
cdpClient.reportError(
`Exception when dispatching message\n' +
'${JSON.stringify(message)}`,
e);
}
}
_getProtocol() {
return new Proxy({}, {
get: (target, domainName, receiver) => new Proxy({}, {
get: (target, methodName, receiver) => {
const eventPattern = /^(on(ce)?|off)([A-Z][A-Za-z0-9]*)/;
const match = eventPattern.exec(methodName);
if (!match) {
return args => this.sendCommand(
`${domainName}.${methodName}`, args || {});
}
let eventName = match[3];
eventName = eventName.charAt(0).toLowerCase() + eventName.slice(1);
if (match[1] === 'once') {
return eventMatcher => this._waitForEvent(
`${domainName}.${eventName}`, eventMatcher);
}
if (match[1] === 'off') {
return listener => this._removeEventHandler(
`${domainName}.${eventName}`, listener);
}
return listener => this._addEventHandler(
`${domainName}.${eventName}`, listener);
},
}),
});
}
_waitForEvent(eventName, eventMatcher) {
return new Promise(callback => {
const handler = result => {
if (eventMatcher && !eventMatcher(result)) {
return;
}
this._removeEventHandler(eventName, handler);
callback(result);
};
this._addEventHandler(eventName, handler);
});
}
_addEventHandler(eventName, handler) {
const handlers = this._eventHandlers.get(eventName) || [];
handlers.push(handler);
this._eventHandlers.set(eventName, handlers);
}
_removeEventHandler(eventName, handler) {
const handlers = this._eventHandlers.get(eventName) || [];
const index = handlers.indexOf(handler);
if (index === -1) {
return;
}
handlers.splice(index, 1);
this._eventHandlers.set(eventName, handlers);
}
}
//
// TargetPage
//
class TargetPage {
constructor(browserSession) {
this._browserSession = browserSession;
this._targetId = '';
this._session;
}
static async create(browserSession) {
const targetPage = new TargetPage(browserSession);
const dp = browserSession.protocol();
const params = {url: 'about:blank'};
const createContextOptions = {};
params.browserContextId =
(await dp.Target.createBrowserContext(createContextOptions))
.result.browserContextId;
targetPage._targetId =
(await dp.Target.createTarget(params)).result.targetId;
const sessionId = (await dp.Target.attachToTarget({
targetId: targetPage._targetId,
flatten: true,
})).result.sessionId;
targetPage._session = browserSession.createSession(sessionId);
return targetPage;
}
targetId() {
return this._targetId;
}
session() {
return this._session;
}
async load(url) {
const dp = this._session.protocol();
await dp.Page.enable();
await dp.Page.setLifecycleEventsEnabled({enabled: true});
const frameId = (await dp.Page.navigate({url})).result.frameId;
await dp.Page.onceLifecycleEvent(
event =>
event.params.name === 'load' && event.params.frameId === frameId);
}
async close() {
const dp = this._session.protocol();
dp.Target.closeTarget({targetId: this._targetId});
}
}
//
// Command handlers
//
async function dumpDOM(dp) {
const script = '(document.doctype ? new ' +
'XMLSerializer().serializeToString(document.doctype) + \'\\n\' : \'\')' +
' + document.documentElement.outerHTML';
const response = await dp.Runtime.evaluate({expression: script});
return response.result.result.value;
}
async function printToPDF(dp, params) {
const displayHeaderFooter = !params.noHeaderFooter;
const generateTaggedPDF = !params.disablePDFTagging;
const printToPDFParams = {
displayHeaderFooter,
generateTaggedPDF,
printBackground: true,
preferCSSPageSize: true,
};
const response = await dp.Page.printToPDF(printToPDFParams);
return response.result.data;
}
async function screenshot(dp, params) {
const format = params.format || 'png';
const screenshotParams = {
format,
};
const response = await dp.Page.captureScreenshot(screenshotParams);
return response.result.data;
}
async function handleCommands(dp, commands) {
const result = {};
if ('dumpDom' in commands) {
result.dumpDomResult = await dumpDOM(dp);
}
if ('printToPDF' in commands) {
result.printToPdfResult = await printToPDF(dp, commands.printToPDF);
}
if ('screenshot' in commands) {
result.screenshotResult = await screenshot(dp, commands.screenshot);
}
return result;
}
//
// Target.exposeDevToolsProtocol() communication functions.
//
function sendDevToolsMessage(json) {
// console.log('[send] ' + json);
window.cdp.send(json);
}
//
// This is called from the host.
//
async function executeCommands(commands) {
window.cdp.onmessage = json => {
// console.log('[recv] ' + json);
cdpClient.dispatchMessage(json);
};
const browserSession = new CDPSession();
const targetPage = await TargetPage.create(browserSession);
const dp = targetPage.session().protocol();
let domContentEventFired = false;
dp.Page.onceDomContentEventFired(() => {
domContentEventFired = true;
});
const promises = [];
let pageLoadTimedOut;
if ('timeout' in commands) {
const timeoutPromise = new Promise(resolve => {
setTimeout(() => {
if (pageLoadTimedOut === undefined) {
pageLoadTimedOut = true;
dp.Page.stopLoading();
}
resolve();
}, commands.timeout);
});
promises.push(timeoutPromise);
}
promises.push(targetPage.load(commands.targetUrl));
await Promise.race(promises);
if (pageLoadTimedOut === undefined) {
pageLoadTimedOut = false;
}
if ('defaultBackgroundColor' in commands) {
await dp.Emulation.setDefaultBackgroundColorOverride(
{color: commands.defaultBackgroundColor});
}
if ('virtualTimeBudget' in commands && !pageLoadTimedOut) {
await dp.Emulation.setVirtualTimePolicy({
budget: commands.virtualTimeBudget,
maxVirtualTimeTaskStarvationCount: 9999,
policy: 'pauseIfNetworkFetchesPending',
});
await dp.Emulation.onceVirtualTimeBudgetExpired();
}
const result = await handleCommands(dp, commands);
// Report timeouts only if we received no content at all.
if (pageLoadTimedOut && !domContentEventFired) {
result.pageLoadTimedOut = true;
}
await targetPage.close();
return result;
}
|