How do I enable media emulation in headless Chrome?

Is there a way to enable simulated device mode or emulated print mode in headless Chrome on Linux?

This can be done manually in DevTools, for example:

Enable substrate emulation

The goal is to take a full screen screenshot in emulated print mode without entering or changing any CSS. I can already take screenshots of web pages using Node.js, but not in emulated print mode. I have searched but also cannot find a useful CLI switch .

Example: StackOverflow print emulation

How can I do this programmatically via CLI or Node.js? Is it possible?


Link to using Node.js to interact with the headless Chrome DevTools protocol: https://developers.google.com/web/updates/2017/04/headless-chrome

-

Update: I researched the Chrome DevTools viewer app in the Emulation section and there is a provision for Emulation.setEmulatedMedia

. setting Emulation.setEmulatedMedia({media: "print"});

displays the page in print emulation mode. In the meantime, there is no need to know about it. ”

+3


source to share


2 answers


The latest (tip-of-tree) documentation on viewing the Chrome DevTools logs in the Emulation section has a section on emulated media. This one line will enable the emulation of the print media:

Emulation.setEmulatedMedia({media: "print"});

      



In addition, if the viewport width is set to 8.5 inches paper width (~ 816px @ 96 DPI), the screenshot will look like a color print preview. In the meantime, there is no need to worry about it. ”

const viewportWidth = 816;    // 8.5 in
const viewportHeight = 1056;  // 11 in

const deviceMetrics = {
    width: viewportWidth,
    height: viewportHeight,
    deviceScaleFactor: 0,
    mobile: false,
    fitWindow: false
};
Emulation.setDeviceMetricsOverride(deviceMetrics);
Emulation.setVisibleSize({width: viewportWidth, height: viewportHeight});

      

+2


source


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!

0


source







All Articles