Interface Route

Whenever a network route is set up with page.route(url, handler[, options]) or browserContext.route(url, handler[, options]), the Route object allows to handle the route.

Learn more about networking.

Hierarchy

  • Route

Methods

  • Aborts the route's request.

    Parameters

    • Optional errorCode: string

      Optional error code. Defaults to failed, could be one of the following:

      • 'aborted' - An operation was aborted (due to user action)
      • 'accessdenied' - Permission to access a resource, other than the network, was denied
      • 'addressunreachable' - The IP address is unreachable. This usually means that there is no route to the specified host or network.
      • 'blockedbyclient' - The client chose to block the request.
      • 'blockedbyresponse' - The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
      • 'connectionaborted' - A connection timed out as a result of not receiving an ACK for data sent.
      • 'connectionclosed' - A connection was closed (corresponding to a TCP FIN).
      • 'connectionfailed' - A connection attempt failed.
      • 'connectionrefused' - A connection attempt was refused.
      • 'connectionreset' - A connection was reset (corresponding to a TCP RST).
      • 'internetdisconnected' - The Internet connection has been lost.
      • 'namenotresolved' - The host name could not be resolved.
      • 'timedout' - An operation timed out.
      • 'failed' - A generic failure occurred.
      Optional

    Returns Promise<void>

  • Continues route's request with optional overrides.

    Usage

    await page.route('**/*', async (route, request) => {
    // Override headers
    const headers = {
    ...request.headers(),
    foo: 'foo-value', // set "foo" header
    bar: undefined, // remove "bar" header
    };
    await route.continue({ headers });
    });

    Details

    Note that any overrides such as url or headers only apply to the request being routed. If this request results in a redirect, overrides will not be applied to the new redirected request. If you want to propagate a header through redirects, use the combination of route.fetch([options]) and route.fulfill([options]) instead.

    Parameters

    • Optional options: {
          headers?: {
              [key: string]: string;
          };
          method?: string;
          postData?: any;
          url?: string;
      }
      Optional
      • Optional headers?: {
            [key: string]: string;
        }

        If set changes the request HTTP headers. Header values will be converted to a string.

        • [key: string]: string
      • Optional method?: string

        If set changes the request method (e.g. GET or POST).

      • Optional postData?: any

        If set changes the post data of request.

      • Optional url?: string

        If set changes the request URL. New URL must have same protocol as original one.

    Returns Promise<void>

  • When several routes match the given pattern, they run in the order opposite to their registration. That way the last registered route can always override all the previous ones. In the example below, request will be handled by the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first registered route.

    Usage

    await page.route('**/*', async route => {
    // Runs last.
    await route.abort();
    });
    await page.route('**/*', async route => {
    // Runs second.
    await route.fallback();
    });
    await page.route('**/*', async route => {
    // Runs first.
    await route.fallback();
    });

    Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for example API calls vs page resources or GET requests vs POST requests as in the example below.

    // Handle GET requests.
    await page.route('**/*', async route => {
    if (route.request().method() !== 'GET') {
    await route.fallback();
    return;
    }
    // Handling GET only.
    // ...
    });

    // Handle POST requests.
    await page.route('**/*', async route => {
    if (route.request().method() !== 'POST') {
    await route.fallback();
    return;
    }
    // Handling POST only.
    // ...
    });

    One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify url, method, headers and postData of the request.

    await page.route('**/*', async (route, request) => {
    // Override headers
    const headers = {
    ...request.headers(),
    foo: 'foo-value', // set "foo" header
    bar: undefined, // remove "bar" header
    };
    await route.fallback({ headers });
    });

    Parameters

    • Optional options: {
          headers?: {
              [key: string]: string;
          };
          method?: string;
          postData?: any;
          url?: string;
      }
      Optional
      • Optional headers?: {
            [key: string]: string;
        }

        If set changes the request HTTP headers. Header values will be converted to a string.

        • [key: string]: string
      • Optional method?: string

        If set changes the request method (e.g. GET or POST).

      • Optional postData?: any

        If set changes the post data of request.

      • Optional url?: string

        If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the route matching, all the routes are matched using the original request URL.

    Returns Promise<void>

  • Performs the request and fetches result without fulfilling it, so that the response could be modified and then fulfilled.

    Usage

    await page.route('https://dog.ceo/api/breeds/list/all', async route => {
    const response = await route.fetch();
    const json = await response.json();
    json.message['big_red_dog'] = [];
    await route.fulfill({ response, json });
    });

    Details

    Note that headers option will apply to the fetched request as well as any redirects initiated by it. If you want to only apply headers to the original request, but not to redirects, look into route.continue([options]) instead.

    Parameters

    • Optional options: {
          headers?: {
              [key: string]: string;
          };
          maxRedirects?: number;
          method?: string;
          postData?: any;
          timeout?: number;
          url?: string;
      }
      Optional
      • Optional headers?: {
            [key: string]: string;
        }

        If set changes the request HTTP headers. Header values will be converted to a string.

        • [key: string]: string
      • Optional maxRedirects?: number

        Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

      • Optional method?: string

        If set changes the request method (e.g. GET or POST).

      • Optional postData?: any

        Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

      • Optional timeout?: number

        Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

      • Optional url?: string

        If set changes the request URL. New URL must have same protocol as original one.

    Returns Promise<APIResponse>

  • Fulfills route's request with given response.

    Usage

    An example of fulfilling all requests with 404 responses:

    await page.route('**/*', async route => {
    await route.fulfill({
    status: 404,
    contentType: 'text/plain',
    body: 'Not Found!'
    });
    });

    An example of serving static file:

    await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));
    

    Parameters

    • Optional options: {
          body?: string | Buffer;
          contentType?: string;
          headers?: {
              [key: string]: string;
          };
          json?: any;
          path?: string;
          response?: APIResponse;
          status?: number;
      }
      Optional
      • Optional body?: string | Buffer

        Response body.

      • Optional contentType?: string

        If set, equals to setting Content-Type response header.

      • Optional headers?: {
            [key: string]: string;
        }

        Response headers. Header values will be converted to a string.

        • [key: string]: string
      • Optional json?: any

        JSON response. This method will set the content type to application/json if not set.

      • Optional path?: string

        File path to respond with. The content type will be inferred from file extension. If path is a relative path, then it is resolved relative to the current working directory.

      • Optional response?: APIResponse

        APIResponse to fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.

      • Optional status?: number

        Response status code, defaults to 200.

    Returns Promise<void>

  • A request to be routed.

    Returns Request

Generated using TypeDoc