0

我想为网页中的单个请求覆盖 ​​cookie 标头。为此,我目前正在使用PuppeteerSharp和 Chrome Devtools Protocol Fetch API(具体来说,我正在使用Fetch.enableFetch.requestPausedFetch.continueRequest)。

请注意,我不想使用Network.setCookie,因为我想绕过浏览器对 cookie 存在的了解。(换句话说,我不希望 cookie 出现在 Chrome DevTools -> Applications -> Cookies 选项卡中)。

我观察到这是间歇性的。如何使此 cookie 覆盖不是间歇性的,而是适用于所有请求?

这是 PuppeteerSharp 代码:(SET THE COOKIE HEADER OVERRIDE重要部分请参见注释)

class Program
{
    public static CDPSession _cdpSession;

    public static void CdpSessionMessageReceived(object sender, MessageEventArgs args)
    {
        if (args.MessageID == "Fetch.requestPaused")
        {
            Task.Run(async () => 
            {
                FetchRequestPausedResponse fetchRequest = args.MessageData.ToObject<FetchRequestPausedResponse>();

                List<Dictionary<string, object>> headers = new List<Dictionary<string, object>>();
                headers.Add(new Dictionary<string, object>
                {
                    { "name", "cookie" },
                    { "value", "abcdefg=1234567" } // SET THE COOKIE HEADER OVERRIDE FOR EVERY REQUEST
                });

                await _cdpSession.SendAsync("Fetch.continueRequest", new Dictionary<string, object>
                    {
                        { "requestId", fetchRequest.RequestId },
                        { "headers", headers.ToArray() }
                    }
                );
            });
        }
    }

    static void Main(string[] args)
    {
        Browser b = await Puppeteer.LaunchAsync(new LaunchOptions()
        {
            ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
            DefaultViewport = null,
            Headless = false
        });

        Page page = b.PagesAsync()[0];

        JObject response = await _cdpSession.SendAsync("Fetch.enable",
            new Dictionary<string, object>
            {
                {
                    "patterns", new Dictionary<string, object>[]
                    {
                        new Dictionary<string, object>
                        {
                            { "urlPattern", "*" }, // URL PATTERN IS * TO INTERCEPT EVERY REQUEST
                            { "requestStage", "Request" }
                        }
                    }
                }
            });

        _cdpSession.MessageReceived += CdpSessionMessageReceived;

        await page.GoToAsync("https://www.google.com");

        await b.CloseAsync();
    }

    internal class FetchRequestPausedResponse
    {
        public string RequestId { get; set; }

        public string NetworkId { get; set; }
    }
}

如果我查看 Chrome DevTools Network 选项卡,我发现 21 个请求中只有 3 个具有abcdefg=1234567cookie 覆盖。下面是一个没有的请求示例: 在此处输入图像描述


更新:在进行更多研究时,chrome.webRequest onBeforeSendHeaders确实可以完成我正在寻找的工作,即在不告诉浏览器 cookie 是什么的情况下覆盖单个请求的 cookie 标头。是一个删除 cookie 标头的代码示例(我找不到以上面 Puppeteer 代码片段的方式替换 cookie 标头的示例)。

现在要弄清楚 PuppeteerSharp 是如何onBeforeSendHeaders做到的......

4

0 回答 0