如何使用 Puppeteer 和 Chrome DevTools 协议修改请求 headers? (可能是 JS 语法问题)
How to modify request headers using Puppeteer & Chrome DevTools Protocol? (Possibly a JS syntax issue)
我有以下 Typescript 函数,假设 Chrome 浏览器已经使用 Puppeteer 启动。可以在 here.
中找到下面使用的 Fetch 函数的文档
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,
});
});
}
这是我看到的具体错误:
Error: Protocol error (Fetch.continueRequest): Invalid parameters headers: array expected
如何解决这个错误并成功修改request.headers
?这是我想不通的愚蠢 Javascript/Typescript 语法问题吗?
Fetch.requestPaused
returns headers 作为 object。例如:
{
"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;
}
我有以下 Typescript 函数,假设 Chrome 浏览器已经使用 Puppeteer 启动。可以在 here.
中找到下面使用的 Fetch 函数的文档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,
});
});
}
这是我看到的具体错误:
Error: Protocol error (Fetch.continueRequest): Invalid parameters headers: array expected
如何解决这个错误并成功修改request.headers
?这是我想不通的愚蠢 Javascript/Typescript 语法问题吗?
Fetch.requestPaused
returns headers 作为 object。例如:
{
"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;
}