Managing print popup in headless Chrome with Selenium C#

I’m working with a headless browser setup and running into issues when trying to control the print dialog. My current approach works fine with a regular browser window, but fails completely when running headless.

IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;

executor.ExecuteScript("window.setTimeout(() => { window.print(); }, 100);");

driver.SwitchTo().Window(driver.WindowHandles[driver.WindowHandles.Count - 1]);

string shadowPath = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('print-preview-button-strip').shadowRoot.querySelector('cr-button.cancel-button')";

IWebElement closeButton = (IWebElement)executor.ExecuteScript($"return {shadowPath}");

closeButton.Click();

The error I get is: OpenQA.Selenium.WebDriverException: JavaScript error: Cannot read property 'shadowRoot' of null

This only happens in headless mode. The same code works perfectly when the browser window is visible. Does anyone know the proper way to handle print dialogs when running Chrome in headless mode?

The print preview interface doesn’t exist in headless Chrome - that’s why your shadowRoot queries aren’t working. Don’t try to manipulate a dialog that isn’t there. Just configure Chrome options to handle printing automatically instead. I ran into this same issue last year and fixed it by adding --disable-print-preview and --print-to-pdf=/path/to/output.pdf to ChromeOptions before starting the driver. This skips the print dialog entirely and saves the PDF directly. Throw in --virtual-time-budget=5000 to make sure the page loads completely before printing. Bottom line: headless mode needs a totally different approach than trying to simulate clicks on UI elements that don’t render.

yep, totally! in headless mode, the print dialog doesn’t show up, so shadowRoot can’t be accessed. try adding --enable-print-browser or use --print-to-pdf option - those should help print without the dialog hassle.

Had this exact problem a few months back and wasted hours debugging the shadowRoot issue. Headless Chrome handles printing completely differently than windowed mode. Don’t fight the print dialog - configure ChromeOptions to bypass it entirely. Add --kiosk-printing and --disable-extensions to your driver options. For PDFs, use --print-to-pdf-no-header with the path argument. Here’s what I figured out: window.print() in headless mode creates PDFs immediately instead of opening a dialog, so there’s nothing to close. Ditch all the dialog manipulation code and let Chrome handle printing natively. Also throw in a brief wait after the print command so file generation finishes before your next operation.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.