Suppose on a page I have this media query:
@media all and (max-width: 800px)
{
div
{
color: green;
}
}
Within the Chrome browser’s DevTools sidebar, I can see this rule and its internal declarations in the Styles tab after inspecting the page.
I want to replicate that ability – to see the declarations within a media query – using Puppeteer and Chrome DevTools Protocol programmatically.
// Launch browser, go to page, create CDP session, enable DOM/CSS/CSS rule usage tracking then:
const { medias } = await cdpSession.send('CSS.getMediaQueries')
console.log(medias)
medias
is an array containing CSSMedia
objects, and it may look something like this:
[
{
text: "(min-width: 800px)",
source: "mediaRule",
sourceURL: "https://example.com/style.css",
range: {
"startLine": 10,
"startColumn": 5,
"endLine": 10,
"endColumn": 25
},
styleSheetId: "id",
mediaList: [
expressions: { value: 800, unit: "px", feature: "max-width", computedLength: 800 },
active: false
]
}
]
So far so good, since this provides some relevant information in a useable format.
But how can I get from this to also retrieving this information, and anything else that may have been declared in the media query:
div
{
color: green;
}
Ideally, it would be good to get the information in the same format as the returned value of CSS.getMediaQueries
but I’m not sure if that’s possible. This describes how to see the rules in the browser itself, as I mentioned above, and the answer mentions the Reveal in source code
feature within the browser. I have a feeling this may mean that Chrome itself may not have such a feature of retrieving serialized objects of affected elements/styles, and just retrieves the string from the source code. Hopefully that isn’t the case.