chrome-har-capturer
Version:
Capture HAR files from a headless Chrome instance
70 lines (63 loc) • 2.09 kB
JavaScript
;
const CDP = require('chrome-remote-interface');
const BROWSER_TARGET = '/devtools/browser';
const VOID_URL = 'about:blank';
class Context {
constructor(options) {
this._cleanup = [];
this._options = options;
}
async create() {
const {host, port, cache} = this._options;
// fetch the browser version (since Chrome 62 the browser target URL is
// generated at runtime and can be obtained via the '/json/version'
// endpoint, fallback to '/devtools/browser' if not present)
const {webSocketDebuggerUrl} = await CDP.Version({host, port});
// connect to the browser target
const browser = await CDP({
host, port,
target: webSocketDebuggerUrl || BROWSER_TARGET,
local: true
});
this._cleanup.unshift(async () => {
await browser.close();
});
const {Target} = browser;
// request a new browser context
let browserContextId;
if (!cache) {
const result = await Target.createBrowserContext();
browserContextId = result.browserContextId;
this._cleanup.unshift(async () => {
await Target.disposeBrowserContext(result);
});
}
// create a new empty tab
const {width, height} = this._options;
const {targetId} = await Target.createTarget({
url: VOID_URL,
width, height,
browserContextId
});
this._cleanup.unshift(async () => {
await Target.closeTarget({targetId});
});
// connect to the tab and return the handler
const tab = await CDP({
host, port,
target: targetId,
local: true
});
this._cleanup.unshift(async () => {
await tab.close();
});
return tab;
}
async destroy() {
// run cleanup handlers
for (const handler of this._cleanup) {
await handler();
}
}
}
module.exports = Context;