0

我正在寻找一种使用无头 chrome 的方法,类似于chromeless所做的,但不是作为 nodejs 端点实现,而是允许将 html 内容作为有效负载的 restful 请求。

我想在通过 API Gateway 触发的 aws lambda 上运行此服务。有没有人有这个用例的经验?

4

1 回答 1

4

没有什么能阻止您在用例中使用 Chromeless。Chromeless 可以在 AWS Lambda 函数中使用。您可以接受来自 AWS API Gateway 的(RESTful)请求,然后用它和 Chromeless 做一些事情。您可以将@serverless-chrome/lambda包与 Chromeless 结合使用,以在 Lambda 中运行无头 Chrome,以便 Chromeless 可以使用 Chrome。Chromeless 代理以类似的方式工作。例如,您的 Lambda 函数的代码可能看起来像(这是我刚刚拼凑起来的未经测试的代码,但应该传达这个想法):

const launchChrome = require('@serverless-chrome/lambda')
const Chromeless = require('chromeless').Chromeless

module.exports.handler = function handler (event, context, callback) {
  const body = JSON.parse(event.body) // event.body coming from API Gateway
  const url = body.url
  const evaluateJs = body.evaluateJs

  launchChrome({
    flags: ['--window-size=1280x1696', '--hide-scrollbars'],
  })
    .then((chrome) => {
      // Chrome is now running on localhost:9222

      const chromeless = new Chromeless({
        launchChrome: false,
      })

      chromeless
        .goto(url)
        .wait('body')
        .evaluate(() => `
          // this will be executed in headless chrome
          ${evaluateJs}
        `)
        .then((result) => {
          chromeless
            .end()
            .then(chrome.kill) // https://github.com/adieuadieu/serverless-chrome/issues/41#issuecomment-317989508
            .then(() => {
              callback(null, {
                statusCode: 200,
                body: JSON.stringify({ result })
              })
            })
        })
        .catch(callback)
    })
    .catch((error) => {
      // Chrome didn't launch correctly
      callback(error)
    })
}

您可以在此处的 Chromeless 问题跟踪器上找到类似的线程。

披露:我是这些包的合作者/作者。

于 2017-08-09T16:16:30.760 回答