-
Notifications
You must be signed in to change notification settings - Fork 321
Load a URL in a separate context (headless mode only)
Andrea Cardaci edited this page Aug 17, 2017
·
2 revisions
Run the usual example code in a new disposable tab in a separated context (think of it as incognito profiles) each time.
const CDP = require('chrome-remote-interface');
async function doInNewContext(action) {
// 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();
// connect to the DevTools special target
const browser = await CDP({
target: webSocketDebuggerUrl || 'ws://localhost:9222/devtools/browser'
});
// create a new context
const {Target} = browser;
const {browserContextId} = await Target.createBrowserContext();
const {targetId} = await Target.createTarget({
url: 'about:blank',
browserContextId
});
// connct to the new context
const client = await CDP({target: targetId});
// perform user actions on it
try {
await action(client);
} finally {
// cleanup
await Target.closeTarget({targetId});
await browser.close();
}
}
// this basically is the usual example
async function example(client) {
// extract domains
const {Network, Page} = client;
// setup handlers
Network.requestWillBeSent((params) => {
console.log(params.request.url);
});
// enable events then start!
await Promise.all([Network.enable(), Page.enable()]);
await Page.navigate({url: 'https://github.com'});
await Page.loadEventFired();
}
doInNewContext(example);