Thanks Jan - yeah, I came across your example and saw the Target object.. and maybe I'm close but not quite - I tried adapting your code to work with my other working example - do you see something obviously wrong here? I don't get an exception, but I'm guessing I previously working code incorrectly in a probably-obvious-to-you way. (Zackary might laugh when he sees this because it's an adaptation of his example code for PDFing screenshots.
var cri = require('chrome-remote-interface');
var tabManagerP;
let resourcesToIgnore = [
];
let viewportSize = {
width: 480,
height: 1000,
};
const outputPath = 'screenshot.png';
function getTabManager () {
if (!tabManagerP) {
tabManagerP = cri({ port: 9222 });
}
return tabManagerP;
}
function executeInTab(workFn) {
return getTabManager()
.then(tabManager => {
return tabManager.Target.createTarget({ url: 'about:blank' })
.then(({ targetId }) => {
return cri.List({ port: 9222 })
.then(list => {
var url = list.find(target =>
target.id === targetId).webSocketDebuggerUrl;
return cri({ tab: url });
})
.then(devtools => workFn(devtools))
.then(result => {
return tabManager.Target.closeTarget({ targetId })
.then(() => result);
}, error => {
return tabManager.Target.closeTarget({ targetId })
.then(() => {
throw error;
});
});
});
});
}
executeInTab(devtools => {
return doSomethingWithDevtools(devtools);
}).then(result => {
console.log(result);
});
function doSomethingWithDevtools(client) {
console.log('doSomethingWithDevtools!!')
const { Emulation, Network, Page } = client;
Emulation.setVisibleSize({
width: viewportSize.width,
height: viewportSize.height,
});
if (resourcesToIgnore && resourcesToIgnore.length) {
resourcesToIgnore.forEach(url => {
console.log('× addBlockedURL', url);
Network.addBlockedURL({
url: url,
});
});
}
Network.requestWillBeSent(params => {
const url = params.request.url;
console.log(`-> ${params.requestId} ${url.substring(0, 150)}`);
});
Network.loadingFailed(params => {
console.log('*** loadingFailed: ', params.requestId);
});
Network.loadingFinished(params => {
console.log('<-', params.requestId, params.encodedDataLength);
});
Page.loadEventFired(
() => {
console.log('loadEventFired!');
setTimeout(() => {
Page.captureScreenshot().then(
v => {
console.log('writing screenshot to', outputPath);
fs.writeFileSync(outputPath, v.data, 'base64');
console.log(`Image saved as ${outputPath}`);
client.close();
}
);
}, 1000);
}
);
return Promise.all([
Network.enable(),
Page.enable()
]).then(() => {
return Page.navigate({ url: targetUrl });
}).catch((err) => {
console.error(`ERROR: ${err.message}`);
client.close();
});