browserless提供了hooks 能力,默认实现都为空,以下简单说明下内部处理

默认实现

如下图

browserless hooks 简单说明_docker

内部处理

  • hooks.ts 定义
import {
  AfterResponse,
  BeforeRequest,
  BrowserHook,
  PageHook,
} from '@browserless.io/browserless';
import { EventEmitter } from 'events';
 
// KEPT for backwards compatibility reasons since some downstream
// docker images will override these files to inject their own hook
// behaviors
// @ts-ignore
import { default as afterRequest } from '../external/after.js';
// @ts-ignore
import { default as beforeRequest } from '../external/before.js';
// @ts-ignore
import { default as browserHook } from '../external/browser.js';
// @ts-ignore
import { default as pageHook } from '../external/page.js';
 
export class Hooks extends EventEmitter {
  before(args: BeforeRequest): Promise<boolean> {
    return beforeRequest(args);
  }
 
  after(args: AfterResponse): Promise<unknown> {
    return afterRequest(args);
  }
 
  page(args: PageHook): Promise<unknown> {
    return pageHook(args);
  }
 
  browser(args: BrowserHook): Promise<unknown> {
    return browserHook(args);
  }
 
  /**
   * Implement any browserless-core-specific shutdown logic here.
   * Calls the empty-SDK stop method for downstream implementations.
   */
  public shutdown = async () => {
    await this.stop();
  };
 
  /**
   * Left blank for downstream SDK modules to optionally implement.
   */
  public stop = () => {};
}
AfterResponse,
  • 使用

如下图,可以看到不少地方都有使用到,核心就是对于几个hooks 的调用

browserless hooks 简单说明_github_02

说明

默认hooks 是放在external 文件夹中的几个文件,如果我们希望自己扩展,就可以重写几个实现,对于基于docker 部署的,直接进行文件替换

参考资料

src/hooks.ts
https://docs.browserless.io/
https://github.com/browserless/browserless