Skip to content

Commit

Permalink
Version 1.0.2
Browse files Browse the repository at this point in the history
  • Loading branch information
Lete114 committed Mar 5, 2022
1 parent 3d1fb65 commit 411119c
Show file tree
Hide file tree
Showing 8 changed files with 228 additions and 12 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ npm run start:hot
| url | | String | 请求的网站 URL 地址,如果输入的是域名会自动拼接`http://` |
| viewport | | Int | 截图 100 宽 200 高,格式`100x200`(需添加`fullPage=false`) |
| isMobile | false | Boolean | 是否是手机端 |
| timeout | 30s | Int | 截图超时,`0`表示无限制 |
| await | 0 | Int | 页面渲染完成后等待,`0`表示不等待(单位毫秒) |
| timeout | 30000 | Int | 截图超时,`0`表示无限制(单位毫秒) |
| waitUntil | load | String | 在什么时机触发截图,[详细请看下方另一个表格 ](#waituntil) |
| fullPage | true | Boolean | 截取完整页面(如果使用`viewport`需要将`fullPage`设置为`false`) |
| type | png | String | 图片类型,`png``jpeg``webp` |
Expand Down
3 changes: 2 additions & 1 deletion README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ Request Method: GET | POST
| url | | String | The URL address of the requested website, if you enter a domain name it will be automatically spelled out as `http://` |
| viewport | | Int | Screenshot 100 wide by 200 high, format `100x200` (need to add `fullPage: false`) |
| isMobile | false | Boolean | Whether it is mobile |
| timeout | 30s | Int | Screenshot timeout, `0` means no limit |
| await | 0 | Int | How long do I wait after the page is rendered,`0` means no waiting (milliseconds) |
| timeout | 30000 | Int | Screenshot timeout, `0` means no limit (milliseconds) |
| waitUntil | load | String | At what time the screenshot is triggered, [see another table below for details](#waituntil) |
| fullPage | true | Boolean | Capture the full page (if using `viewport` you need to set `fullPage` to `false`) |
| type | png | String | The image type, `png`, `jpeg`, `webp` |
Expand Down
Binary file added font/WenQuanDengKuanWeiMiHei-1.ttf
Binary file not shown.
166 changes: 165 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "webstack-screenshot",
"version": "1.0.1",
"version": "1.0.2",
"description": "网站截图 API | Website Screenshot API ",
"main": "index.js",
"scripts": {
Expand Down Expand Up @@ -31,7 +31,9 @@
},
"dependencies": {
"body-data": "^1.0.2",
"puppeteer": "^13.4.1"
"chrome-aws-lambda": "^10.1.0",
"puppeteer": "^13.4.1",
"puppeteer-core": "^13.4.1"
},
"devDependencies": {
"eslint": "^8.10.0",
Expand Down
43 changes: 36 additions & 7 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
const puppeteer = require('puppeteer')
const bodyData = require('body-data')
const { goto, screenshot, isBoolean } = require('./utils')
const { launch, goto, screenshot, isBoolean } = require('./utils')

/*eslint-disable max-statements */
module.exports = async (req, res) => {
let browser = null
try {
if (req.url === '/favicon.ico') return res.end()
const data = await bodyData(req)
Expand All @@ -12,7 +13,11 @@ module.exports = async (req, res) => {
return res.end(JSON.stringify({ msg: 'URL not detected' }))
}

const browser = await puppeteer.launch()
// 判断是服务器(Server)还是无服务器(ServerLess),决定使用Chromium
const launchOpt = await launch()

browser = await puppeteer.launch(launchOpt)

const page = await browser.newPage()

// 设置截图宽高比
Expand All @@ -30,23 +35,47 @@ module.exports = async (req, res) => {
const gotoOpt = goto(data) // 打开网站选项
await page.goto(data.url, gotoOpt)

// 页面渲染完成后等待(毫秒)
await page.waitForTimeout(gotoOpt.await)

// 截图
const options = screenshot(data) // 截图选项
const content = await page.screenshot(options)
const screenshotOpt = screenshot(data) // 截图选项
const content = await page.screenshot(screenshotOpt)

// 关闭浏览器
// 每次关闭浏览器后,下次再次使用会重新启动浏览器,消耗性能(消耗几百毫秒的启动时间)
// 可直接关闭标签页来提高性能 `await page.close()`
// 或是保留标签页到缓存中,如果一直被请求同一个url那么直接使用缓存里的标签页(会增加服务器内存消耗,但能道极高的请求响应速度)
// 如果你想优化,欢迎你PR哦~(其实我就是懒才直接关闭浏览器的)
await browser.close()

res.setHeader('Content-Type', 'image/' + options.type)
res.write(content, options.encoding)
if (options.encoding === 'base64') {
// 响应base64的img标签
if (screenshotOpt.encoding === 'base64') {
const base64 = `data:image/${screenshotOpt.type};base64,${content}`
res.setHeader('Content-Type', 'text/html; charset=utf-8')

// img 标签
const styleImg = 'style=display:block;margin:auto;cursor:zoom-in;'
const img = `<img src=${base64} ${styleImg}>`

// body 标签
const styleBody = 'style=margin:0px;background:#0e0e0e;height:100%;'
const body = `<body ${styleBody}>${img}</body>`
res.write(body)
} else {
// 直接响应图片
res.setHeader('Content-Type', 'image/' + screenshotOpt.type) // 响应图片类型
res.write(content, screenshotOpt.encoding)
}
res.end()
} catch (error) {
// eslint-disable-next-line
console.error(error)
res.end(JSON.stringify({ msg: 'Screenshot failed' }))
} finally {
if (browser !== null) {
await browser.close()
}
}
}
/* eslint-enable max-statements */
1 change: 1 addition & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const http = require('http')
const main = require('./main')

async function init(PORT) {
process.env.PUPPETEER_SERVER = true
PORT = process.env.PORT || PORT || 6870
const server = http.createServer(main)
server.listen(PORT, () => {
Expand Down
18 changes: 18 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
const { join } = require('path')
const chromium = require('chrome-aws-lambda')

function isBoolean(value) {
return value === 'true' || value === true ? true : false
}

module.exports = {
async launch() {
// 设置字体
const fontPath = join(__dirname, '../font/WenQuanDengKuanWeiMiHei-1.ttf')
await chromium.font(fontPath)

const chromiumOptions = {
args: chromium.args,
executablePath: await chromium.executablePath,
headless: chromium.headless
}
return process.env.PUPPETEER_SERVER ? {} : chromiumOptions
},
goto(data) {
const options = {}

Expand All @@ -12,6 +27,9 @@ module.exports = {
// 超时,默认30s
if (!isNaN(data.timeout)) options.timeout = Math.abs(data.timeout) ?? 30000

// 页面渲染完成后等待(毫秒)
if (!isNaN(data.await)) options.await = Math.abs(data.await) || 0

// 什么模式下截图
if (data.waitUntil) {
const opt = {
Expand Down

0 comments on commit 411119c

Please sign in to comment.