How to enable print media emulation in headless Chrome?
In the latest (tip-of-tree) Chrome DevTools Protocol Viewer documentation under Emulation, there is a section about emulated media. This one line will enable print media emulation:
Emulation.setEmulatedMedia({media: "print"});
In addition, if the viewport width is set to that of an 8.5in sheet of paper (~816px @ 96 DPI), then the screenshot will resemble a color print preview.
const viewportWidth = 816; // 8.5 inconst viewportHeight = 1056; // 11 inconst deviceMetrics = { width: viewportWidth, height: viewportHeight, deviceScaleFactor: 0, mobile: false, fitWindow: false};Emulation.setDeviceMetricsOverride(deviceMetrics);Emulation.setVisibleSize({width: viewportWidth, height: viewportHeight});
Figured out how to do this using in Django (python) with Selenium and Chromedriver.
def set_media_emulation(self, media): """ This is used to trigger between print mode and screen to allow @media (print) css styles to take effect call this in your testcase like self.set_media_emulation('print') or self.set_media_emulation('screen') :param media: :return: """ command_url = "/session/{session_id}/chromium/send_command".format(session_id=self.selenium.session_id) self.selenium.command_executor._commands["send_command"] = ("POST", command_url) params = {'cmd': 'Emulation.setEmulatedMedia', 'params': {'media': media}} return self.selenium.execute("send_command", params)
Where self.selenium
is
from selenium.webdriver import Chromeself.selenium = Chrome(desired_capabilities=desired_capabilities, options=chrome_options, service_args=['--verbose'], service_log_path=self.selenium_log_path)
For anyone looking for this, I figured out how to do it for Rspec+capybara+selenium:
def enable_print_emulation bridge = Capybara.current_session.driver.browser.send(:bridge) path = "/session/#{bridge.session_id}/chromium/send_command" bridge.http.call(:post, path, cmd: 'Emulation.setEmulatedMedia', params: {media: 'print'})end
Then just call this method in your spec!