【问题标题】:How to modify request headers using Puppeteer & Chrome DevTools Protocol? (Possibly a JS syntax issue)如何使用 Puppeteer 和 Chrome DevTools 协议修改请求标头? (可能是 JS 语法问题)
【发布时间】:2019-08-21 17:57:39
【问题描述】:

我有以下 Typescript 函数,假设 Chrome 浏览器已经使用 Puppeteer 启动。下面使用的 Fetch 函数的文档可以在 here 找到。

async function modify(client: CDPSession) {
    client.on('Fetch.requestPaused', async ({ requestId, request, frameId, resourceType, responseErrorReason, responseStatusCode, responseHeaders, networkId }) => {
        // Correctly prints out the User-Agent header's value
        console.log(request.headers["User-Agent"]);

        // After this line is run, I can inspect the request.headers object and see that User-Agent was successfully edited
        request.headers['User-Agent'] = 'trying to edit this header';

        // Continuing the request gives an error
        await client.send('Fetch.continueRequest', {
            requestId: requestId,
            headers: request.headers,
        });
    });
}

这是我看到的具体错误:

错误:协议错误(Fetch.continueRequest):无效参数标头:预期数组

如何解决此错误并成功修改request.headers?这是我无法弄清楚的愚蠢的 Javascript/Typescript 语法问题吗?

【问题讨论】:

  • send函数中的headers是数组,所以需要设置[{name: 'User-Agent', value: 'trying to edit this header'}]

标签: javascript node.js typescript puppeteer chrome-devtools-protocol


【解决方案1】:

Fetch.requestPaused 将标头作为对象返回。例如:

{
    "Upgrade-Insecure-Requests":"1",
    "Accept": "text/html,application/xhtml+xml"}
}

Fetch.continueRequest 需要 Array<{name: string, value: string}>。例如

[
    {"name": "Accept", value: "text/html,application/xhtml+xml"}
]

您可以使用 Puppeteer 正在使用的代码:

function headersArray(headers) {
  const result = [];
  for (const name in headers) {
    if (!Object.is(headers[name], undefined))
      result.push({name, value: headers[name] + ''});
  }
  return result;
}

【讨论】:

  • 不幸的是使用headersArray 函数,我仍然收到此错误消息:错误:协议错误(Fetch.continueRequest):无效参数标头:预期数组
  • 第二次尝试,它正在工作。我一定没有对 Typescript 项目进行 Visual Studio 重建。谢谢!将您的答案标记为已接受。
猜你喜欢
  • 2020-01-11
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多