Skip to main content
Version: 23.8.0

Page.setRequestInterception() 方法

¥Page.setRequestInterception() method

激活请求拦截会启用 HTTPRequest.abort()HTTPRequest.continue()HTTPRequest.respond() 方法。这提供了修改页面发送的网络请求的能力。

¥Activating request interception enables HTTPRequest.abort(), HTTPRequest.continue() and HTTPRequest.respond() methods. This provides the capability to modify network requests that are made by a page.

一旦启用请求拦截,每个请求都会停止,除非继续、响应或中止;或者使用浏览器缓存完成。

¥Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.

有关详细信息,请参阅 请求拦截指南

¥See the Request interception guide for more details.

签名

¥Signature

class Page {
abstract setRequestInterception(value: boolean): Promise<void>;
}

参数

¥Parameters

范围

类型

描述

value

boolean

是否启用请求拦截。

Returns:

Promise<void>

示例

¥Example

中止所有图片请求的简单请求拦截器的示例:

¥An example of a naïve request interceptor that aborts all image requests:

import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (
interceptedRequest.url().endsWith('.png') ||
interceptedRequest.url().endsWith('.jpg')
)
interceptedRequest.abort();
else interceptedRequest.continue();
});
await page.goto('https://example.com');
await browser.close();
})();