puppeteer stop redirect 的正確姿式及 net::ERR_FAILED 的解決

在官方文檔(puppeteer/api.md at master · GoogleChrome/puppeteer · GitHub)中,中斷 redirect 的標準作法是這樣的:git

const puppeteer = require('puppeteer');

puppeteer.launch().then(async browser => {
  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();
});

這樣一開始也是沒有什麼問題,可是偶爾會遇到這樣狀況:github

Error: net::ERR_FAILED at http://xxx.com/yyyapi

Google 了一輪,發現相關的 issue 不多,只找到了這麼一個:
Page.setRequestInterception Redirection Issue · Issue #3421 · GoogleChrome/puppeteer · GitHubasync

官方已經把它定義爲一個 Bug 了,也有一些相關的解決方案:umbrella Fix Request Interception · Issue #3471 · GoogleChrome/puppeteer · GitHubui

不過其餘人遇到的狀況是 abort() 以後沒法結束的問題,而我是拋出異常的問題,因此我本身摸索了一下,總結出一個比較合適的辦法:
就是用 respond 代替 abort。url

好比:code

// request.abort();
request.respond({
  status: 404,
  contentType: 'text/plain',
  body: 'Not Found!',
});
相關文章
相關標籤/搜索