Skip to content

Add support for scraping CSS-in-JS based styles πŸ‘©β€πŸŽ€ #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
node_modules
package-lock.json
6,954 changes: 6,954 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

25 changes: 13 additions & 12 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,18 @@ module.exports = async (
// but not all...
const coverage = await page.coverage.stopCSSCoverage()

// Fetch all <style> tags from the page, because the coverage
// API may have missed some JS-generated <style> tags.
// Some of them *were* already caught by the coverage API,
// but they will be removed later on to prevent duplicates.
const styleTagsCss = (await page.$$eval('style', styles => {
// Get the text inside each <style> tag and trim() the
// results to prevent all the inside-html indentation
// clogging up the results and making it look
// bigger than it actually is
return styles.map(style => style.innerHTML.trim())
})).join('')
// Get all CSS generated with the CSSStyleSheet API
// See: https://developer.mozilla.org/en-US/docs/Web/API/CSSRule/cssText
const styleSheetsApiCss = await page.evaluate(() => {
/* global document */
return [...document.styleSheets]
.map(stylesheet =>
[...stylesheet.cssRules]
.map(cssStyleRule => cssStyleRule.cssText)
.join('')
)
.join('')
})

await browser.close()

Expand All @@ -73,5 +74,5 @@ module.exports = async (
.map(({text}) => text)
.join('')

return Promise.resolve(coverageCss + styleTagsCss)
return Promise.resolve(styleSheetsApiCss + coverageCss)
}
53 changes: 39 additions & 14 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ const puppeteerCore = require('puppeteer-core')
const extractCss = require('..')

let server
const expected = readFileSync(resolve(__dirname, 'fixture.css'), 'utf8')
const fixture = readFileSync(resolve(__dirname, 'fixture.css'), 'utf8')

test.before(async () => {
server = await createTestServer()

server.get('/fixture.css', (req, res) => {
res.send(expected)
res.send(fixture)
})
})

Expand All @@ -27,11 +27,16 @@ test('it fetches css from a page with CSS in a server generated <link> inside th
server.get(url, (req, res) => {
res.send(`
<!doctype html>
<link rel="stylesheet" href="fixture.css" />
<html>
<head>
<link rel="stylesheet" href="fixture.css" />
</head>
</html>
`)
})

const actual = await extractCss(server.url + url)
const expected = fixture

t.is(actual, expected)
})
Expand All @@ -41,13 +46,14 @@ test('it fetches css from a page with CSS in server generated <style> inside the
server.get(url, (req, res) => {
res.send(`
<!doctype html>
<style>${expected.trim()}</style>
<style>${fixture}</style>
`)
})

const actual = await extractCss(server.url + url)
const expected = 'body { color: teal; }'

t.is(actual, expected.trim())
t.is(actual, expected)
})

test('it finds JS generated <link /> CSS', async t => {
Expand All @@ -62,6 +68,7 @@ test('it finds JS generated <link /> CSS', async t => {
})

const actual = await extractCss(server.url + path)
const expected = fixture

t.is(actual, expected)
})
Expand All @@ -77,7 +84,26 @@ test('it finds JS generated <style /> CSS', async t => {
})

const actual = await extractCss(server.url + url, {waitUntil: 'load'})
const expected = `body { color: teal; }`
const expected = 'body { color: teal; }'

t.is(actual, expected)
})

test('it finds css-in-js, like Styled Components', async t => {
const url = '/css-in-js'
const cssInJsExampleHtml = readFileSync(
resolve(__dirname, 'css-in-js.html'),
'utf8'
)
server.get(url, (req, res) => {
res.send(cssInJsExampleHtml)
})

const actual = await extractCss(server.url + url, {waitUntil: 'load'})
// Color is RGB instead of Hex, because of serialization:
// https://www.w3.org/TR/cssom-1/#serializing-css-values
const expected =
'html { color: rgb(255, 0, 0); }.hJHBhT { color: blue; font-family: sans-serif; font-size: 3em; }'

t.is(actual, expected)
})
Expand All @@ -94,9 +120,11 @@ test('it combines server generated <link> and <style> tags with client side crea

const actual = await extractCss(server.url + path)

t.true(actual.includes('content: "js-style";'))
t.true(actual.includes('content: "server-style";'))
t.true(actual.includes(`body {`))
t.true(actual.includes(`color: teal;`))
t.snapshot(actual)
t.true(actual.includes('counter-increment: 2;'))
t.true(actual.includes('counter-increment: 3;'))
})

test('it rejects if the url has an HTTP error status', async t => {
Expand All @@ -116,20 +144,17 @@ test('it accepts a browser override for usage with other browsers', async t => {
res.send(`
<!doctype html>
<style>
body::before {
content: ${req.headers['user-agent']};
}
body::before { content: "${req.headers['user-agent']}"; }
</style>
`)
})
const customBrowser = await puppeteerCore.launch({
executablePath: chromium.path,
args: ["--user-agent='Extract CSS Core'"]
args: ['--user-agent=Extract CSS Core']
})
const actual = await extractCss(server.url + path, {customBrowser})

t.snapshot(actual)
t.true(actual.includes("content: 'Extract CSS Core';"))
t.is(actual, 'body::before { content: "Extract CSS Core"; }')
})

test('it rejects on an invalid customBrowser option', async t => {
Expand Down
7 changes: 4 additions & 3 deletions test/kitchen-sink.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,18 @@

<!-- Server generated style -->
<style>
.server-style {
counter-increment: 2;
.server-style::after {
content: 'server-style';
}
</style>

<h1>Title</h1>
<div class="server-style">server-style:</div>

<script>
// Client generated style
var style = document.createElement('style')
style.textContent = '.js-style { counter-increment: 3; }'
style.textContent = '.js-style::after { content: "js-style"; }'
document.body.appendChild(style)

// Client generated link
Expand Down
14 changes: 2 additions & 12 deletions test/snapshots/index.js.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,14 @@ The actual snapshot is saved in `index.js.snap`.

Generated by [AVA](https://ava.li).

## it accepts a browser override for usage with other browsers

> Snapshot 1

`body::before {␊
content: 'Extract CSS Core';␊
}`

## it combines server generated <link> and <style> tags with client side created <link> and <style> tags

> Snapshot 1

`body {␊
`.server-style::after { content: "server-style"; }.js-style::after { content: "js-style"; }body {␊
color: teal;␊
}␊
body {␊
color: teal;␊
}␊
.server-style {␊
counter-increment: 2;␊
}.js-style { counter-increment: 3; }`
`
Binary file modified test/snapshots/index.js.snap
Binary file not shown.