I’m trying to simulate mobile page rendering and testing in Chrome using Playwright. I need to activate the Toggle Device Toolbar via the Ctrl+Shift+M keyboard shortcut within the DevTools panel.
Here’s my code:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({
headless: false,
devtools: true // enable developer tools
});
const context = await browser.newContext();
const page = await context.newPage();
// create cdp session
const client = await context.newCDPSession(page);
// activate devtools
await client.send('Page.enable');
await client.send('Page.bringToFront');
await client.send('Page.navigate', { url: 'Some url' });
// get devTools targetId
const targets = await client.send('Target.getTargets', {});
const devToolsTargetId = targets.targetInfos.find((info) => info.type === 'other').targetId;
// focus on devtools panel
// await client.send('Target.activateTarget', { targetId: devToolsTargetId });
await client.send('Target.attachToTarget', { targetId: devToolsTargetId });
// simulate shortcuts: Ctrl + Shift + M
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown',
modifiers: 8, // means 'Ctrl+Shift'
windowsVirtualKeyCode: 77, // means key 'M'
nativeVirtualKeyCode: 77,
autoRepeat: false,
isKeypad: false,
targetId: devToolsTargetId,
});
await client.send('Input.dispatchKeyEvent', {
type: 'keyUp',
modifiers: 8,
windowsVirtualKeyCode: 77,
nativeVirtualKeyCode: 77,
autoRepeat: false,
isKeypad: false,
targetId: devToolsTargetId,
});
// Do something on the page, e.g., take a screenshot
await page.screenshot({ path: 'screenshot.png' });
// await browser.close();
})();
This code opens Chrome with DevTools, navigates to a URL, attempts to focus on the DevTools panel with ‘Target.attachToTarget’, and sends the simulated key events for ‘Ctrl+Shift+M’ with ‘Input.dispatchKeyEvent’. However, the Toolbar doesn’t get activated.
The output of ‘targets.targetInfos’ is:
[
{
targetId: 'CBF44E36684FD28034D2543C684754A5',
type: 'other',
title: '',
url: 'devtools://devtools/bundled/devtools_app.html?remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/@f4095e9665f7d7a2531edefcea119d45d899d95b/&can_dock=true&targetType=tab',
attached: true,
canAccessOpener: false,
browserContextId: '91C311D78E340D26C7A07F56F6EE4198'
},
{
targetId: '214735BD67A2224755912F57CDBF353E',
type: 'page',
title: 'about:blank',
url: 'Some url',
attached: true,
canAccessOpener: false,
browserContextId: '68E0C79153C5A7951F11E74D4482AE57'
}
]
My question is: why isn’t the Toggle Device Toolbar activating when I simulate the Ctrl+Shift+M shortcut in the DevTools panel? How can I fix this behavior?