Headless chrome launcher - window dependent bug
I need to take a screenshot of a specific window size. I read this blog http://phptest.club/t/how-to-run-headless-chrome-in-codeception/1544 and this page https://developers.google.com/web/updates/2017/04/ headless-chrome , but couldn't figure out how to resize the window on initialization.
I tried to pass --window-size
in all parameters below and none works:
- window size = 1280,1696
- window size = 1280x1696
- window size 1280,1696
- window size 1280x1696
Worst of all , now my screenshot is blank after doing this for some time. Is there some memory saved in a non-browser browser causing this? I haven't tried restarting the Mac yet, but probably the next one.
So what is the way to get a full screenshot of the page at a given window size? In phantom.js, this is a very trivial thing.
My code is below
const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
const file = require('fs');
(async function() {
async function launchChrome() {
return await chromeLauncher.launch({
chromeFlags: [
'--window-size=1280,1696',
'--disable-gpu',
'--headless'
]
});
}
const chrome = await launchChrome();
const protocol = await CDP({
port: chrome.port
});
const {
DOM,
Network,
Page,
Emulation,
Runtime
} = protocol;
await Promise.all([Network.enable(), Page.enable(), Runtime.enable(), DOM.enable()]);
Page.navigate({
url: 'https://www.yahoo.com/'
});
Page.loadEventFired(async() => {
console.log('Start Page.loadEventFired');
const script1 = "document.querySelector('p').textContent"
const result = await Runtime.evaluate({
expression: script1
});
console.log(result.result.value);
const ss = await Page.captureScreenshot({format: 'png', fromSurface: false});
file.writeFile('output.png', ss.data, 'base64', function(err) {
if (err) {
console.log(err);
}
});
protocol.close();
chrome.kill();
});
})();
If I do this on the command line, it works great:
alias chrome-canary="/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary"
chrome-canary --headless --disable-gpu --screenshot --window-size=300,1696 https://www.yahoo.com/
UPDATE 1
I figured out that headless Chrome Canary is at least unstable on Mac. If I close the terminal and start it, then someday it works. But after he executed the exact same script, he just hung up for good (I left for the night). I just updated everything (Chrome Canary, chrome-launcher, chrome-remote-interface) today and continue to debug. Maybe this is not the main time.
source to share
OK I just found out that using --window-size
it won't work. Below work:
Added:
Page.setDeviceMetricsOverride({
'width': 735,
'height': 2200,
'deviceScaleFactor': 1,
'mobile': false
});
Removed (forces Chrome to freeze without freezing):
const script1 = "document.querySelector('p').textContent"
const result = await Runtime.evaluate({
expression: script1
});
console.log(result.result.value);
source to share