To run Chrome browser in a headless environment, we need send an aurgument "--headless" to ChromeOptions. This option will tell Google Chrome to execute in headless mode.
Earlier most of the headless options were standalone tools and were seperate from the browsers, such as HTMLUnit or PhantomJS. Now Google has implemented a headless option for Chrome using all the modern web platform features provided by Chromium and Blink.
Note:- Chrome Headless is available on Mac and Linux from Chrome v59 and for Windows it is from Chrome v60.
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");
Now you can also use a single line command options.setHeadless(true) which does the same job of adding the above two arguments.
Still having this problem as of Chrome 61, so I spent a while looking for a different solution. My favorite because of it's simplicity is injecting javascript before the alert is shown in order to automatically accept the alert.
Just put the following line of code before the line that causes the alert to be shown:
That BEFORE is crucial. So guys put this line before the element.click() and just to add for python do driver.execute_script("window.confirm = function(){return true;}"); – Alex PasSep 8 '17 at 16:17
Engineer @ Google working on web tooling: Headless Chrome, Puppeteer, Lighthouse
TL;DR
Headless Chrome is shipping in Chrome 59. It's a way to run the Chrome browser in a headless environment. Essentially, running Chrome without chrome! It brings all modern web platform features provided by Chromium and the Blink rendering engine to the command line.
Why is that useful?
A headless browser is a great tool for automated testing and server environments where you don't need a visible UI shell. For example, you may want to run some tests against a real web page, create a PDF of it, or just inspect how the browser renders an URL.
Starting Headless (CLI)
The easiest way to get started with headless mode is to open the Chrome binary from the command line. If you've got Chrome 59+ installed, start Chrome with the --headless flag:
chrome \ --headless \# Runs Chrome in headless mode. --disable-gpu \# Temporarily needed if running on Windows. --remote-debugging-port=9222\ https://www.chromestatus.com # URL to open. Defaults to about:blank.
chrome should point to your installation of Chrome. The exact location will vary from platform to platform. Since I'm on Mac, I created convenient aliases for each version of Chrome that I have installed.
If you're on the stable channel of Chrome and cannot get the Beta, I recommend using chrome-canary:
alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome" alias chrome-canary="/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary" alias chromium="/Applications/Chromium.app/Contents/MacOS/Chromium"
Running with --screenshot will produce a file named screenshot.png in the current working directory. If you're looking for full page screenshots, things are a tad more involved. There's a great blog post from David Schnurr that has you covered. Check out Using headless Chrome as an automated screenshot tool .
REPL mode (read-eval-print loop)
The --repl flag runs Headless in a mode where you can evaluate JS expressions in the browser, right from the command line:
$ chrome --headless --disable-gpu --repl --crash-dumps-dir=./tmp https://www.chromestatus.com/ [0608/112805.245285:INFO:headless_shell.cc(278)]Type a Javascript expression to evaluate or"quit" to exit. >>> location.href {"result":{"type":"string","value":"https://www.chromestatus.com/features"}} >>> quit
$
Debugging Chrome without a browser UI?
When you run Chrome with --remote-debugging-port=9222, it starts an instance with the DevTools protocol enabled. The protocol is used to communicate with Chrome and drive the headless browser instance. It's also what tools like Sublime, VS Code, and Node use for remote debugging an application. #synergy
Since you don't have browser UI to see the page, navigate to http://localhost:9222 in another browser to check that everything is working. You'll see a list of inspectable pages where you can click through and see what Headless is rendering:
DevTools remote debugging UI
From here, you can use the familiar DevTools features to inspect, debug, and tweak the page as you normally would. If you're using Headless programmatically, this page is also a powerful debugging tool for seeing all the raw DevTools protocol commands going across the wire, communicating with the browser.
Using programmatically (Node)
Puppeteer
Puppeteer is a Node library developed by the Chrome team. It provides a high-level API to control headless (or full) Chrome. It's similar to other automated testing libraries like Phantom and NightmareJS, but it only works with the latest versions of Chrome.
Among other things, Puppeteer can be used to easily take screenshots, create PDFs, navigate pages, and fetch information about those pages. I recommend the library if you want to quickly automate browser testing. It hides away the complexities of the DevTools protocol and takes care of redundant tasks like launching a debug instance of Chrome.
chrome-remote-interface is a lower-level library than Puppeteer's API. I recommend it if you want to be close to the metal and use the DevTools protocol directly.
Launching Chrome
chrome-remote-interface doesn't launch Chrome for you, so you'll have to take care of that yourself.
In the CLI section, we started Chrome manually using --headless --remote-debugging-port=9222. However, to fully automate tests, you'll probably want to spawn Chrome from your application.
But things get tricky if you want a portable solution that works across multiple platforms. Just look at that hard-coded path to Chrome :(
Using ChromeLauncher
Lighthouse is a marvelous tool for testing the quality of your web apps. A robust module for launching Chrome was developed within Lighthouse and is now extracted for standalone use. The chrome-launcher NPM module will find where Chrome is installed, set up a debug instance, launch the browser, and kill it when your program is done. Best part is that it works cross-platform thanks to Node!
By default, chrome-launcher will try to launch Chrome Canary (if it's installed), but you can change that to manually select which Chrome to use. To use it, first install from npm:
npm i --save chrome-launcher
Example - using chrome-launcher to launch Headless
const chromeLauncher =require('chrome-launcher');
// Optional: set logging level of launcher to see its output. // Install it using: npm i --save lighthouse-logger // const log = require('lighthouse-logger'); // log.setLevel('info');
/**
* Launches a debugging instance of Chrome.
* @param {boolean=} headless True (default) launches Chrome in headless mode.
* False launches a full version of Chrome.
* @return {Promise<ChromeLauncher>}
*/ function launchChrome(headless=true){ return chromeLauncher.launch({ // port: 9222, // Uncomment to force a specific port of your choice. chromeFlags:[ '--window-size=412,732', '--disable-gpu', headless ?'--headless':'' ] }); }
Running this script doesn't do much, but you should see an instance of Chrome fire up in the task manager that loaded about:blank. Remember, there won't be any browser UI. We're headless.
To control the browser, we need the DevTools protocol!
// Extract the DevTools protocol domains we need and enable them. // See API docs: https://chromedevtools.github.io/devtools-protocol/ const{Page}= protocol; await Page.enable();
// Extract the DevTools protocol domains we need and enable them. // See API docs: https://chromedevtools.github.io/devtools-protocol/ const{Page,Runtime}= protocol; await Promise.all([Page.enable(),Runtime.enable()]);
// Wait for window.onload before doing stuff. Page.loadEventFired(async ()=>{ const js ="document.querySelector('title').textContent"; // Evaluate the JS expression in the page. const result = await Runtime.evaluate({expression: js});
console.log('Title of page: '+ result.result.value);
Right now, Selenium opens a full instance of Chrome. In other words, it's an automated solution but not completely headless. However, Selenium can be configured to run headless Chrome with a little work. I recommend Running Selenium with Headless Chrome if you want the full instructions on how to set things up yourself, but I've dropped in some examples below to get you started.
Using ChromeDriver
ChromeDriver 2.32 uses Chrome 61 and works well with headless Chrome.
// Navigate to google.com, enter a search. driver.get('https://www.google.com/'); driver.findElement({name:'q'}).sendKeys('webdriver'); driver.findElement({name:'btnG'}).click(); driver.wait(webdriver.until.titleIs('webdriver - Google Search'),1000);
// Take screenshot of results page. Save to disk. driver.takeScreenshot().then(base64png =>{ fs.writeFileSync('screenshot.png',newBuffer(base64png,'base64')); });
driver.quit();
Using WebDriverIO
WebDriverIO is a higher level API on top of Selenium WebDriver.
const title = await browser.getTitle(); console.log(`Title: ${title}`);
await browser.waitForText('.num-features',3000); let numFeatures = await browser.getText('.num-features'); console.log(`Chrome has ${numFeatures} total features`);
Lighthouse - automated tool for testing web app quality; makes heavy use of the protocol
chrome-launcher - node module for launching Chrome, ready for automation
Demos
"The Headless Web" - Paul Kinlan's great blog post on using Headless with api.ai.
FAQ
Do I need the --disable-gpu flag?
Only on Windows. Other platforms no longer require it. The --disable-gpu flag is a temporary work around for a few bugs. You won't need this flag in future versions of Chrome. See crbug.com/737678 for more information.
So I still need Xvfb?
No. Headless Chrome doesn't use a window so a display server like Xvfb is no longer needed. You can happily run your automated tests without it.
What is Xvfb? Xvfb is an in-memory display server for Unix-like systems that enables you to run graphical applications (like Chrome) without an attached physical display. Many people use Xvfb to run earlier versions of Chrome to do "headless" testing.
How do I create a Docker container that runs Headless Chrome?
Headless Chrome is similar to tools like PhantomJS. Both can be used for automated testing in a headless environment. The main difference between the two is that Phantom uses an older version of WebKit as its rendering engine while Headless Chrome uses the latest version of Blink.
At the moment, Phantom also provides a higher level API than the DevTools protocol.
Where do I report bugs?
For bugs against Headless Chrome, file them on crbug.com.
element.click()
and just to add for python dodriver.execute_script("window.confirm = function(){return true;}");
– Alex Pas Sep 8 '17 at 16:17