Skip to content

Instantly share code, notes, and snippets.

@meddulla
Created May 14, 2024 15:50
Show Gist options
  • Save meddulla/8d0df337441cc7516c3f9fa227ab765c to your computer and use it in GitHub Desktop.
Save meddulla/8d0df337441cc7516c3f9fa227ab765c to your computer and use it in GitHub Desktop.
Cloudflare puppeteer response.text()
import puppeteer from "@cloudflare/puppeteer";
// deploy with $ npx wrangler deploy
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const path = url.pathname
let reqUrl = url.searchParams.get("url") || 'https://example.com';
reqUrl = new URL(reqUrl).toString(); // normalize
console.log(`path:${path} - reqUrl:${reqUrl}`)
let browser = await puppeteer.launch(env.MYBROWSER);
const sessionId = browser.sessionId()
const page = await browser.newPage();
const response = await page.goto(reqUrl);
const dom = await response!.text()
await browser.close()
const html = `${sessionId}
--------------------------
${dom}`
return new Response(html, {
headers: {
"content-type": "text/plain",
},
});
},
};
{
"dependencies": {
"wrangler": "^3.24.0",
"@cloudflare/puppeteer": "^0.0.7"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20230221.0",
"@types/node": "^18.11.18",
"@types/service-worker-mock": "^2.0.1",
"ts-node": "^10.9.1",
"typescript": "^4.9.5",
"wrangler": "^3.6.0"
}
}
name = "response-text"
main = "index.ts"
compatibility_date = "2023-03-14"
node_compat = true
browser = { binding = "MYBROWSER"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment