簡體   English   中英

如何使用 Puppeteer 和 Chrome DevTools 協議修改請求標頭? (可能是JS語法問題)

[英]How to modify request headers using Puppeteer & Chrome DevTools Protocol? (Possibly a JS syntax issue)

我有以下 Typescript 函數,假設已經使用 Puppeteer 啟動了 Chrome 瀏覽器。 下面使用的 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,
        });
    });
}

這是我看到的具體錯誤:

錯誤:協議錯誤(Fetch.continueRequest):無效的參數標頭:需要數組

如何解決此錯誤並成功修改request.headers 這是我無法弄清楚的愚蠢的 Javascript/Typescript 語法問題嗎?

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM