I have a working Selenium script that opens Chrome and navigates to web pages. The problem is that I can see the browser window opening every time my script runs. I want to make the browser run in the background without showing any visible window.
Here’s what I’m currently using:
const { Builder } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');
const serviceBuilder = new chrome.ServiceBuilder(chromedriver.path);
chrome.setDefaultService(serviceBuilder.build());
const browser = new Builder()
.forBrowser('chrome')
.build();
browser.get('https://www.example.com/profile/john-doe');
browser.getTitle().then(function(pageTitle) {
console.log(pageTitle);
});
How can I modify this code to run Chrome in headless mode so the browser window stays hidden during execution?
You’ll need to set a window size when running headless - there’s no default viewport. I ran into this when my scripts started breaking because elements weren’t rendering right. Add --window-size=1920,1080 to your Chrome options with the headless flag. If you’re on Linux servers or containers, throw in --no-sandbox and --disable-dev-shm-usage too - prevents memory issues that crash headless sessions. Without proper window dimensions, responsive sites act weird and your selectors won’t work.
You need to create a chrome options object and pass it to the builder. Here’s the fix:
const options = new chrome.Options();
options.addArguments('--headless');
options.addArguments('--disable-gpu'); // recommended for headless
const browser = new Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
I’ve used this setup for months in production - works great. The disable-gpu flag isn’t always needed but prevents rendering issues on some systems. Just make sure you’re importing the Options class correctly or you’ll get undefined errors.
just add the headless option to your chrome options first. do options.addArguments('--headless') then pass it to the builder with .setChromeOptions(options). worked great for me!