使用Puppeteer在Cloudflare上部署浏览器渲染Worker的详细指南

54 min read

使用Puppeteer在Cloudflare上部署浏览器渲染Worker的详细指南

这篇将介绍如何在Cloudflare上利用Puppeteer库部署浏览器渲染Worker。

通过创建一个Cloudflare Worker,浏览器渲染API从网页中获取截图,适用于各种浏览器自动化任务。

Cloudflare Worker是由Cloudflare提供的一项服务,它允许开发者在全球分布的云网络中运行JavaScript代码。Worker充当你应用程序的中间层,可以用于执行各种任务,包括处理HTTP请求、修改和优化内容、执行自定义逻辑等

先决条件

在开始之前的准备工作:

  1. 注册一个Cloudflare账户。
  2. 安装npm和Node.js,建议使用版本16.17.0或更高。你可以使用Node版本管理器(如Volta或nvm)来管理Node.js版本,以避免权限问题。
  3. 已获取CF的waitlist的批准 https://www.cloudflare.com/lp/workers-browser-rendering-api/

步骤

1. 创建Worker项目

首先,使用以下命令在本地创建一个新的Cloudflare Worker项目:

npm create cloudflare@latest

选项参考如下:

base) ➜  ~ npm create cloudflare@latest
Need to install the following packages:
[email protected]
Ok to proceed? (y)

using create-cloudflare version 2.9.0

╭ Create an application with Cloudflare Step 1 of 3
├ In which directory do you want to create your application?
│ dir ./cf-test
│
├ What type of application do you want to create?
│ type "Hello World" Worker
│
├ Do you want to use TypeScript?
│ yes typescript
│
├ Copying files from "hello-world" template
│
├ Retrieving current workerd compatibility date
│ compatibility date 2023-12-18
│
├ Do you want to use git for version control?
│ yes git
│
╰ Application created

╭ Installing dependencies Step 2 of 3
│
├ Installing dependencies
│ installed via `npm install`
│
├ Installing @cloudflare/workers-types
│ installed via npm
│
├ Adding latest types to `tsconfig.json`
│ added @cloudflare/workers-types/2023-07-01
│
├ Committing new files
│ git commit
│
╰ Dependencies Installed

╭ Deploy with Cloudflare Step 3 of 3
│
├ Do you want to deploy your application?
│ yes deploy via `npm run deploy`
│
├ Logging into Cloudflare checking authentication status
│ not logged in
│
├ Logging into Cloudflare This will open a browser window
│ allowed via `wrangler login`
│
├ Selecting Cloudflare account retrieving accounts
│ account [email protected]'s Account
│
├ Deploying your application

2. 安装Puppeteer

在项目目录中,通过以下命令安装Cloudflare的Puppeteer版本:

npm install @cloudflare/puppeteer --save-dev

3. 创建KV命名空间

浏览器渲染可能需要与其他开发者产品一起使用,例如关系数据库、R2存储桶、Durable Object或Queues。

创建两个命名空间,一个用于生产环境,一个用于开发环境:创建 KV(键-值)存储命名空间是为了在 Cloudflare Workers 中使用 KV 存储。在 Workers 中存储和检索数据,如在本教程中用于缓存截图。

示例:

# 为生产环境创建 KV 命名空间 命令将创建一个名为 BROWSER_KV_PRODUCTION 的 KV 命名空间
npx wrangler kv:namespace create BROWSER_KV_PRODUCTION

# 为开发环境创建 KV 命名空间 命令将创建一个名为 BROWSER_KV_DEVELOPMENT 的 KV 命名空间
# 并使用 --preview 标志表示这是用于开发环境的预览命名空间
npx wrangler kv:namespace create BROWSER_KV_DEVELOPMENT --preview

命令分别会输出一个id 一个 preview_id

4. 配置 wrangler.toml

Wrangler 是 Cloudflare Workers 的官方命令行工具,用于管理和部署 Workers 项目。它简化了与 Cloudflare Workers 服务的交互,使得开发者能够更轻松地创建、测试和部署他们的 Workers 代码

在项目的wrangler.toml文件中,添加浏览器渲染API绑定和KV命名空间的配置:

name = "browser-worker"
main = "src/index.js"
compatibility_date = "2023-03-14"
compatibility_flags = [ "nodejs_compat" ]

browser = { binding = "MYBROWSER" }
kv_namespaces = [
  { binding = "BROWSER_KV_DEMO", id = "22cf855786094a88a6906f8edac425cd", preview_id = "e1f8b68b68d24381b57071445f96e623" }
]

wrangler.toml 文件中的kv_namespaces配置部分,

id是用于生产环境的命名空间ID

preview_id是用于开发环境的命名空间ID。

5. 编写Worker代码

src/index.js中更新Worker代码,实现从指定URL获取截图并缓存到KV存储:

import puppeteer from "@cloudflare/puppeteer";

export default {
	async fetch(request, env) {
		const { searchParams } = new URL(request.url);
		let url = searchParams.get("url");
		let img;
		if (url) {
			url = new URL(url).toString();
			img = await env.BROWSER_KV_DEMO.get(url, { type: "arrayBuffer" });
			if (img === null) {
				const browser = await puppeteer.launch(env.MYBROWSER);
				const page = await browser.newPage();
				await page.goto(url);
				img = await page.screenshot();
				await env.BROWSER_KV_DEMO.put(url, img, {
					expirationTtl: 60 * 60 * 24,
				});
				await browser.close();
			}
			return new Response(img, {
				headers: {
					"content-type": "image/jpeg",
				},
			});
		} else {
			return new Response(
				"Please add an ?url=https://example.com/ parameter"
			);
		}
	},
};

6. 本地测试

运行以下命令进行本地测试:

npx wrangler dev --remote

通过访问 <LOCAL_HOST_URL>/?url=https://example.com 测试获取截图。

7. 部署

使用以下命令将Worker部署到Cloudflare全球网络:

npx wrangler deploy

通过访问 <YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev/?url=https://example.com 查看已部署的Worker。