2017-11-01 15:44:27 +00:00
|
|
|
import puppeteer from 'puppeteer'
|
|
|
|
|
|
|
|
let browser = null
|
|
|
|
|
2017-11-02 13:24:20 +00:00
|
|
|
export async function start(options = {}) {
|
2017-11-01 15:44:27 +00:00
|
|
|
// https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions
|
2017-11-02 13:24:20 +00:00
|
|
|
browser = await puppeteer.launch(Object.assign({
|
2017-11-01 15:44:27 +00:00
|
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
2017-11-02 13:24:20 +00:00
|
|
|
}, options))
|
2017-11-01 15:44:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function stop() {
|
|
|
|
if (!browser) return
|
|
|
|
await browser.close()
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function page(url) {
|
|
|
|
if (!browser) throw new Error('Please call start() before page(url)')
|
|
|
|
const page = await browser.newPage()
|
|
|
|
await page.goto(url)
|
|
|
|
await page.waitForFunction('!!window.$nuxt')
|
|
|
|
page.html = () => page.evaluate(() => window.document.documentElement.outerHTML)
|
|
|
|
page.$text = (selector) => page.$eval(selector, (el) => el.textContent)
|
2017-11-02 13:24:20 +00:00
|
|
|
page.$$text = (selector) => page.$$eval(selector, (els) => els.map((el) => el.textContent))
|
2017-11-02 16:47:50 +00:00
|
|
|
page.$attr = (selector, attr) => page.$eval(selector, (el, attr) => el.getAttribute(attr), attr)
|
|
|
|
page.$$attr = (selector, attr) => page.$$eval(selector, (els, attr) => els.map((el) => el.getAttribute(attr)), attr)
|
2017-11-01 15:44:27 +00:00
|
|
|
page.$nuxt = await page.evaluateHandle('window.$nuxt')
|
|
|
|
|
|
|
|
page.nuxt = {
|
2017-11-07 15:26:15 +00:00
|
|
|
async navigate(path, waitEnd = true) {
|
2017-11-07 15:55:54 +00:00
|
|
|
const hook = page.evaluate(() => {
|
|
|
|
return new Promise((resolve) => window.$nuxt.$once('routeChanged', resolve))
|
|
|
|
.then(() => new Promise((resolve) => setTimeout(resolve, 50)))
|
2017-11-07 15:26:15 +00:00
|
|
|
})
|
2017-11-01 15:44:27 +00:00
|
|
|
await page.evaluate(($nuxt, path) => $nuxt.$router.push(path), page.$nuxt, path)
|
2017-11-07 15:26:15 +00:00
|
|
|
if (waitEnd) await hook
|
|
|
|
return { hook }
|
2017-11-01 15:44:27 +00:00
|
|
|
},
|
2017-11-02 13:24:20 +00:00
|
|
|
routeData() {
|
|
|
|
return page.evaluate(($nuxt) => {
|
|
|
|
return {
|
|
|
|
path: $nuxt.$route.path,
|
|
|
|
query: $nuxt.$route.query
|
|
|
|
}
|
|
|
|
}, page.$nuxt)
|
|
|
|
},
|
2017-11-01 15:44:27 +00:00
|
|
|
loadingData() {
|
|
|
|
return page.evaluate(($nuxt) => $nuxt.$loading.$data, page.$nuxt)
|
|
|
|
},
|
2017-11-02 16:47:50 +00:00
|
|
|
errorData() {
|
|
|
|
return page.evaluate(($nuxt) => $nuxt.nuxt.err, page.$nuxt)
|
|
|
|
},
|
2017-11-02 17:07:33 +00:00
|
|
|
storeState() {
|
|
|
|
return page.evaluate(($nuxt) => $nuxt.$store.state, page.$nuxt)
|
2017-11-01 15:44:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return page
|
|
|
|
}
|