Possible to run Headless Chrome/Chromium in a Google Cloud Function?

前端 未结 4 782
臣服心动
臣服心动 2020-12-14 03:29

Is there any way to run Headless Chrome/Chromium in a Google Cloud Function? I understand I can include and run statically compiled binaries in GCF. Can I get a statically c

4条回答
  •  感动是毒
    2020-12-14 03:55

    I've just deployed a GCF function running headless Chrome. A couple takeways:

    1. you have to statically compile Chromium and NSS on Debian 8
    2. you have to patch environment variables to point to NSS before launching Chromium
    3. performance is much worse than what you'd get on AWS Lambda (3+ seconds)

    For 1, you should be able to find plenty of instructions online.

    For 2, the code that I'm using is the following:

    static executablePath() {
      let bin = path.join(__dirname, '..', 'bin', 'chromium');
      let nss = path.join(__dirname, '..', 'bin', 'nss', 'Linux3.16_x86_64_cc_glibc_PTH_64_OPT.OBJ');
    
      if (process.env.PATH === undefined) {
        process.env.PATH = path.join(nss, 'bin');
      } else if (process.env.PATH.indexOf(nss) === -1) {
        process.env.PATH = [path.join(nss, 'bin'), process.env.PATH].join(':');
      }
    
      if (process.env.LD_LIBRARY_PATH === undefined) {
        process.env.LD_LIBRARY_PATH = path.join(nss, 'lib');
      } else if (process.env.LD_LIBRARY_PATH.indexOf(nss) === -1) {
        process.env.LD_LIBRARY_PATH = [path.join(nss, 'lib'), process.env.LD_LIBRARY_PATH].join(':');
      }
    
      if (fs.existsSync('/tmp/chromium') === true) {
        return '/tmp/chromium';
      }
    
      return new Promise(
        (resolve, reject) => {
          try {
            fs.chmod(bin, '0755', () => {
              fs.symlinkSync(bin, '/tmp/chromium'); return resolve('/tmp/chromium');
            });
          } catch (error) {
            return reject(error);
          }
        }
      );
    }
    

    You also need to use a few required arguments when starting Chrome, namely:

    --disable-dev-shm-usage
    --disable-setuid-sandbox
    --no-first-run
    --no-sandbox
    --no-zygote
    --single-process
    

    I hope this helps.

提交回复
热议问题