Created
July 11, 2020 15:22
-
-
Save frank-dspeed/9f4889beecd107d2fa50066b96af2937 to your computer and use it in GitHub Desktop.
Use Puppeteer to interact with the DevTools UI while inspecting a page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use Puppeteer to interact with the DevTools UI while inspecting a page | |
// This is a complete hack, but it allows you to interact with the DevTools UI using Puppeteer. | |
// In this example, I'm able to install Adblock Plus and navigate to the extension's tab | |
const puppeteer = require('puppeteer'); | |
(async() => { | |
// launch with devtools, which enables debugging capabilities | |
// and load the Adblock extension (assumes the unpacked extension is in a folder called `adblock-unpacked`) | |
const browser = await puppeteer.launch({ | |
devtools: true, | |
args: [ | |
'--disable-extensions-except=adblock-unpacked', | |
'--load-extension=adblock-unpacked/', | |
] | |
}); | |
const wsEndpoint = browser.wsEndpoint(); | |
// the page I want to debug | |
const myPage = await browser.newPage(); | |
const pageId = myPage.target()._targetId; | |
// use the host:port that Chromium provided, but replace the browser endpoint with the page to inspect | |
const pageTargeUrl = `${wsEndpoint.replace('ws://', '').match(/.*(?=\/browser)/)[0]}/page/${pageId}`; | |
// generate the full debugging url for the page I want to inspect | |
const pageDebuggingUrl = `chrome-devtools://devtools/bundled/devtools_app.html?ws=${pageTargeUrl}`; | |
// open the debugging UI in a new tab that Puppeteer can interact with | |
const devtoolsPage = await browser.newPage(); | |
await devtoolsPage.goto(pageDebuggingUrl); | |
// navigate to the page now so that we start capturing data in the debugger UI | |
await myPage.goto('http://news.bbc.co.uk'); | |
// the installed extension may open a new tab so make sure we select the debugger UI tab | |
await devtoolsPage.bringToFront() | |
// use Cmd + ] shortut to move across tabs until we're on the the Adblock Plus tab | |
let selectedAdblockTab = null; | |
while (!selectedAdblockTab) { | |
await devtoolsPage.keyboard.down('MetaLeft'); | |
await devtoolsPage.keyboard.press(']'); | |
await devtoolsPage.keyboard.up('MetaLeft'); | |
selectedAdblockTab = await devtoolsPage.evaluate(() => { | |
return document.querySelector('#-blink-dev-tools > div.widget.vbox.root-view > div > div > div').shadowRoot.querySelector('#tab-chrome-extension\\\:\\\/\\\/cfhdojbkjhnklbpkdaibdccddilifddbAdblockPlus[aria-selected="true"]'); | |
}) | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment