screenshoteer/index.js

70 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-12-02 12:06:38 +01:00
#!/usr/bin/env node
const puppeteer = require('puppeteer')
const devices = require('puppeteer/DeviceDescriptors')
const program = require('commander')
var urlvalue, emulate = "";
program
.option('--url, [url]', 'The url')
.option('--emulate, [emulate]', 'emulate device')
.option('--fullpage, [fullpage]', 'Full Page')
.option('--pdf, [pdf]', 'Generate PDF')
.option('--w, [w]', 'width')
.option('--h, [h]', 'height')
2018-12-04 13:38:32 +01:00
.option('--waitfor, [waitfor]', 'Wait time in milliseconds')
2018-12-04 16:23:06 +01:00
.option('--el, [el]', 'element css selector')
2018-12-06 11:32:21 +01:00
.option('--auth, [auth]', 'Basic HTTP authentication')
2018-12-02 12:06:38 +01:00
.parse(process.argv);
if (program.url) urlvalue = program.url
else process.exit(console.log("Please add --url parameter. Something like this: $ screenshoteer --url http:www.example.com"));
2018-12-05 18:05:07 +01:00
!program.fullpage ? fullPage = true : fullPage = JSON.parse(program.fullpage);
2018-12-02 12:06:38 +01:00
console.log(urlvalue);
console.log(fullPage);
(async () => {
2018-12-05 17:00:18 +01:00
try {
await execute();
} catch(e) {
console.error(e);
process.exit(1);
}
async function execute() {
const browser = await puppeteer.launch()
const page = await browser.newPage()
const d = new Date()
if (program.w && program.h) await page.setViewport({width: Number(program.w), height: Number(program.h)})
if (program.emulate) await page.emulate(devices[program.emulate]);
2018-12-06 11:32:21 +01:00
if (program.auth) {
const [username, password] = program.auth.split(':');
await page.authenticate({username:username, password:password});
}
2018-12-05 17:00:18 +01:00
await page.goto(urlvalue)
const title = await page.title()
const t = title.replace(/[/\\?%*:|"<>]/g, '-')
if (program.waitfor) await page.waitFor(Number(program.waitfor))
if (program.el) {
const el = await page.$(program.el);
await el.screenshot({
path: `${t} ${program.emulate} ${program.el} ${d.getTime()}.png`
});
} else {
await page.screenshot({path: t + " " + program.emulate + " " + d.getTime() + '.png', fullPage: fullPage})
}
await page.emulateMedia('screen')
if (program.pdf) await page.pdf({ path: t + " " + program.emulate + " " + d.getTime() + '.pdf' })
console.log(t)
await browser.close()
2018-12-04 16:23:06 +01:00
}
2018-12-05 17:00:18 +01:00
2018-12-02 12:06:38 +01:00
})()
2018-12-05 17:00:18 +01:00