Beware that --start-maximized
flag doesn't work in a headless mode. Then you have to set window size, e.g. like so: --window-size=1920,1040
.
The way you can do it is you define both options in config:
config.json:
{
"browserOptions": {
"headless": {
"headless": true,
"args": [
"--window-size=1920,1040"
],
"defaultViewport": null
},
"gui": {
"headless": false,
"args": [
"--start-maximized"
],
"defaultViewport": null
}
}
}
and you choose which one to use based on an env variable - you can implement a tiny module for that:
Helpers/browserOption.js:
require('dotenv').config();
const config = require('../config.json');
module.exports = {
browserConfig: () => {
if (process.env.BROWSER === "headless") {
return config.browserOptions.headless;
}
return config.browserOptions.gui;
}
};
then if you set env variable BROWSER
to headless
, the concrete window size will be set upon browser launch, and if you choose to run your script in a non-headless mode, --start-maximized
arg will be used.
In a script, it could be used like so:
const browserOption = require('./Helpers/browserOption');
const browser - await puppeteer.launch(browserOption.browserConfig());