CEFSharp 通过自定义处理程序更改用户代理

问题描述 投票:0回答:1

对于使用 cefsharp 项目还是很陌生。

我正在尝试将用户代理绑定到一个实例而不是全局。

目前我在我的 Program.cs 中使用以下内容

var settings = new CefSettings();
settings.CefCommandLineArgs.Add("user-agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1");

虽然这有效,但它会全局设置用户代理。我使用两种表单,因为我希望一种报告为移动设备,另一种报告为桌面设备。这样做,我对如何做到这一点感到困惑。使用上面的内容,它正在全局设置 UserAgent。我讨厌必须注释和取消注释设置它的行。

我尝试了以下方法

using CefSharp;
using CefSharp.Handler;

public class CustomRequestHandler : CefSharp.Handler.RequestHandler
{
    protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
    {
        // Intercept only the specific URL
        if (request.Url == "https://www.whatismybrowser.com/detect/what-is-my-user-agent")
        {
            request.SetHeaderByName("user-agent", "MyBrowser CefSharp Browser", true);
        }

        // Always return false to continue the navigation
        return false;
    }
}

我认为我对其进行了正确的调整,但现在遇到了 IRequest 是只读的事实。尝试了其他几种调整,总是遇到只读问题。

编辑:好的,我想我在这里做了一些事情。

using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Specialized;

public class CustomRequestHandler : RequestHandler
{
    protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
    {
        if (request.Url == "https://www.whatismybrowser.com/detect/what-is-my-user-agent")
        {
            try
            {
                // Log the interception of the URL
                Console.WriteLine("Intercepted URL: " + request.Url);

                // Create a dictionary to hold the modified headers
                var modifiedHeaders = new NameValueCollection(request.Headers);

                // Modify the user agent
                modifiedHeaders["user-agent"] = "MyBrowser CefSharp Browser";

                // Create a new request with the modified headers
                var modifiedRequest = frame.CreateRequest();
                modifiedRequest.Url = request.Url;
                modifiedRequest.Method = request.Method;
                modifiedRequest.Headers = modifiedHeaders;

                // Copy post data if it exists
                if (request.PostData != null)
                {
                    modifiedRequest.PostData = request.PostData;
                }

                // Load the modified request using the browser
                frame.LoadRequest(modifiedRequest);

                // Log successful loading of the modified request
                Console.WriteLine("Modified request loaded successfully.");

                return true; // Cancel the original request
            }
            catch (Exception ex)
            {
                // Log any exceptions for debugging purposes
                Console.WriteLine("Exception occurred: " + ex.Message);
            }
        }

        return false; // Continue with the original request
    }
}

使用这段代码,它实际上不会加载测试网址,而是会加载其他网址。所以它实际上是在处理测试 url。它只是不会实际加载页面。它只是按预期拦截移动浏览器。 拦截的 URL:https://www.whatismybrowser.com/detect/what-is-my-user-agent 修改后的请求加载成功。

最新的代码似乎拦截了 url 并使用我的处理程序,我必须做一些日志记录才能得到这个

OnBeforeBrowse URL: https://www.whatismybrowser.com/detect/what-is-my-user-agent
Intercepted URL: https://www.whatismybrowser.com/detect/what-is-my-user-agent
Modified request loaded successfully.
Load Error: Aborted, ERR_ABORTED, https://www.whatismybrowser.com/detect/what-is-my-user-agent
Loading State Changed: False
[14956:7864:0710/043123.774:ERROR:bad_message.cc(29)] Terminating renderer for bad IPC message, reason 213
GetResourceRequestHandler: https://csm.us5.us.criteo.net/iev?entry=c~Gum.ChromeSyncframe.CookieRead.uid~1&entry=c~Gum.ChromeSyncframe.FragmentData.onetag.Bundle.Origin.undefined~1&entry=c~Gum.ChromeSyncframe.SidReadSuccess~1&entry=h~Gum.ChromeSyncframe.SidReadSuccessDuration~328
Render process terminated: ProcessCrashed

[8352:10124:0710/040922.537:ERROR:bad_message.cc(29)] Terminating renderer for bad IPC message, reason 213
[8352:10124:0710/040922.538:VERBOSE1:browser_info_manager.cc(531)] frame 6-BB0DCBA5339448D1441249D75553904F, pdf_process=0, browser_process_guest=0, print_preview_dialog=0, main=1
[8352:10124:0710/040922.542:VERBOSE1:frame_host_impl.cc(515)] frame A-F5DF7D801E84FDC36BCC535A08C6FD9B (sub) detached (reason=RENDER_FRAME_DELETED, is_connected=1)
[8352:10124:0710/040922.543:VERBOSE1:frame_host_impl.cc(515)] frame 9-870ABD8F28E33A0A82F7D99F90C14289 (sub) detached (reason=RENDER_FRAME_DELETED, is_connected=1)
[18420:11048:0710/040922.543:VERBOSE1:network_delegate.cc(35)] NetworkDelegate::NotifyBeforeURLRequest: https://csm.us5.us.criteo.net/iev?entry=c~Gum.ChromeSyncframe.CookieRead.uid~1&entry=c~Gum.ChromeSyncframe.FragmentData.onetag.Bundle.Origin.undefined~1&entry=c~Gum.ChromeSyncframe.SidReadSuccess~1&entry=h~Gum.ChromeSyncframe.SidReadSuccessDuration~676
[8352:10124:0710/040922.544:VERBOSE1:frame_host_impl.cc(515)] frame 8-A5EA056889DFBED6602D2F909E9971D4 (sub) detached (reason=RENDER_FRAME_DELETED, is_connected=1)

使用禁用站点隔离试验命令行,页面仍然无法加载,浏览器处于无限循环中不断刷新页面的状态。

c# ipc user-agent cefsharp
1个回答
0
投票

好吧,我不知道为什么我有这么多问题。也许只是我还在学习,并不真正知道自己在做什么。我的错。

https://gist.github.com/amaitland/0b05701710064203171bfd05f5002514#file-setuseragentoverrideasync-cs

amaitland 暗示的这个解决方案有效。

© www.soinside.com 2019 - 2024. All rights reserved.