CefSharp 中过滤图片 RequestHandler

CefSharp 中过滤图片 RequestHandler【C#CefSharp过滤RequestHandler图片1、方式一ChromiumWebBrowser实现IRequestHandler具体内同参照附录;将OnBeforeResourceLoad方法替换成2中的内容,很简单;2、方式二继承集成默认的抽象类DefaultRequestHandlerinternalclassRequestHandler…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

【C# CefSharp 过滤 RequestHandler 图片

1、方式一 ChromiumWebBrowser 实现 IRequestHandler

具体内同参照 附录;将 OnBeforeResourceLoad方法替换成2中的内容,很简单;


2、方式二 继承集成默认的抽象类 DefaultRequestHandler

 internal class RequestHandler : DefaultRequestHandler 
    {

        public  override CefReturnValue  OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
        {

            if (request.ResourceType == ResourceType.Image)
                return CefReturnValue.Cancel;

            return CefReturnValue.Continue;
        }
}

对比实现接口方式和继承集成默认的抽象类,发现抽象类可以只实现相关的处理方法更加灵活。而若采用IRequestHandler需要实现RequestHandler接口中的所有方法,否则抛出未实现异常;


和其他网上从Response环节过滤资源图片的方法不同,这里谈到的方法在请求图片资源之前,可以节省流量,加快页面访问速度等。

附录:

using System;
using CefSharp.Example.Filters;
using System.Security.Cryptography.X509Certificates;
using System.Collections.Generic;
using System.Text;
using CefSharp.Handler;

namespace CefSharp.Example.Handlers
{
    /// <summary>
    /// DefaultRequestHandler provides a base class for you to inherit from 
    /// you only need to implement the methods that are relevant to you. 
    /// If you implement the IRequestHandler interface you will need to
    /// implement every method
    /// </summary>
    public class RequestHandler : IRequsetHandler
    {
        public static readonly string VersionNumberString = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}",
            Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);

        private Dictionary<UInt64, MemoryStreamResponseFilter> responseDictionary = new Dictionary<UInt64, MemoryStreamResponseFilter>();

        public override bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
        {
            return false;
        }

        public override bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
        {
            return false;
        }

        public override bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    //To allow certificate
                    //callback.Continue(true);
                    //return true;
                }
            }

            return false;
        }

        public override void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
        {
            // TODO: Add your own code here for handling scenarios where a plugin crashed, for one reason or another.
        }

        public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
        {
            Uri url;
            if (Uri.TryCreate(request.Url, UriKind.Absolute, out url) == false)
            {
                //If we're unable to parse the Uri then cancel the request
                // avoid throwing any exceptions here as we're being called by unmanaged code
                return CefReturnValue.Cancel;
            }

            //Example of how to set Referer
            // Same should work when setting any header

            // For this example only set Referer when using our custom scheme
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                //Referrer is now set using it's own method (was previously set in headers before)
                request.SetReferrer("http://google.com", ReferrerPolicy.Default);
            }

            //Example of setting User-Agent in every request.
            //var headers = request.Headers;

            //var userAgent = headers["User-Agent"];
            //headers["User-Agent"] = userAgent + " CefSharp";

            //request.Headers = headers;

            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    if (request.Method == "POST")
                    {
                        using (var postData = request.PostData)
                        {
                            if(postData != null)
                            { 
                                var elements = postData.Elements;

                                var charSet = request.GetCharSet();

                                foreach (var element in elements)
                                {
                                    if (element.Type == PostDataElementType.Bytes)
                                    {
                                        var body = element.GetBody(charSet);
                                    }
                                }
                            }
                        }
                    }

                    //Note to Redirect simply set the request Url
                    //if (request.Url.StartsWith("https://www.google.com", StringComparison.OrdinalIgnoreCase))
                    //{
                    //    request.Url = "https://github.com/";
                    //}

                    //Callback in async fashion
                    //callback.Continue(true);
                    //return CefReturnValue.ContinueAsync;
                }
            }

            return CefReturnValue.Continue;
        }

        public override bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.

            callback.Dispose();
            return false;
        }

        public override bool OnSelectClientCertificate(IWebBrowser browserControl, IBrowser browser, bool isProxy, string host, int port, X509Certificate2Collection certificates, ISelectClientCertificateCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            callback.Dispose();
            return false;
        }

        public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
        {
            // TODO: Add your own code here for handling scenarios where the Render Process terminated for one reason or another.
            browserControl.Load(CefExample.RenderProcessCrashedUrl);
        }

        public override bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    //Accept Request to raise Quota
                    //callback.Continue(true);
                    //return true;
                }
            }

            return false;
        }

        public override void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl)
        {
            //Example of how to redirect - need to check `newUrl` in the second pass
            //if (request.Url.StartsWith("https://www.google.com", StringComparison.OrdinalIgnoreCase) && !newUrl.Contains("github"))
            //{
            //    newUrl = "https://github.com";
            //}
        }

        public override bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
        {
            return url.StartsWith("mailto");
        }

        public override void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
        {

        }

        public override bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            //NOTE: You cannot modify the response, only the request
            // You can now access the headers
            //var headers = response.Headers;

            return false;
        }

        public override IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var url = new Uri(request.Url);
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                if(request.Url.Equals(CefExample.ResponseFilterTestUrl, StringComparison.OrdinalIgnoreCase))
                {
                    return new FindReplaceResponseFilter("REPLACE_THIS_STRING", "This is the replaced string!");
                }

                if (request.Url.Equals("custom://cefsharp/assets/js/jquery.js", StringComparison.OrdinalIgnoreCase))
                {
                    return new AppendResponseFilter(System.Environment.NewLine + "//CefSharp Appended this comment.");
                }

                //Only called for our customScheme
                var dataFilter = new MemoryStreamResponseFilter();
                responseDictionary.Add(request.Identifier, dataFilter);
                return dataFilter;
            }

            //return new PassThruResponseFilter();
            return null;
        }

        public override void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            var url = new Uri(request.Url);
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                MemoryStreamResponseFilter filter;
                if(responseDictionary.TryGetValue(request.Identifier, out filter))
                {
                    //TODO: Do something with the data here
                    var data = filter.Data;
                    var dataLength = filter.Data.Length;
                    //NOTE: You may need to use a different encoding depending on the request
                    var dataAsUtf8String = Encoding.UTF8.GetString(data);                
                }
            }
        }
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/191724.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • C# Modbus 通讯

    C# Modbus 通讯SpSetup类与Globalspace类publicpartialclassSpSetup:Form{#region定义变量///<summary>///发送报文///</summary>publicbyte[]sendData=ne…

  • 对象转map工具类BeanUtil

    对象转map工具类BeanUtil1、2、当isAccessible()的结果是false时不允许通过反射访问private变量。packagecom.yung.ppapi.util;importjava.beans.BeanInfo;importjava.beans.Introspector;importjava.beans.PropertyDescriptor;importjava.lang.re…

  • gb28181协议详解_GB28181收费吗

    gb28181协议详解_GB28181收费吗ssdp协议近似于http协议,事实上,和http协议相似得地方就是他得协议内容,当然,我们要去除他得端口和d类地址。为什么我在给其他员工或者面试得时候要他人深入一些,理解一下http协议,是因为理解了http协议,掌握ssdp也就不远了,很多人可能会问http协议有啥内容,无非就是get,post,put,delete么,还能怎么样,我经常问他们一点http协议怎么知道他结束了?虽然ssdp是udp协议,但是他依然需要\r\n来代表行结束,\r\n\r\n代表协议内容部分结束。……

    2022年10月11日
  • Navicat premium15 激活码【2022免费激活】2022.03.10

    (Navicat premium15 激活码)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容https://javaforall.cn/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~1M2OME2TZY-eyJsaWNlb…

  • win7 java修复工具哪个好_DLL修复工具哪个好

    win7 java修复工具哪个好_DLL修复工具哪个好为什么会用到dll修复工具呢?因为在打开某些程序或者软件的时候会提示找不到某某.dll文件,关键是这些dll文件还不一样,去网上下载这些dll文件结果显示跟系统的版本不一致,反正就是各种麻烦,自己去找又费时又费力,而且往往对于有些游戏来说,修补了某一个dll又提示缺少另一个dll文件,这些其实可能都是系统本身太精简或者没有安装一些依赖软件导致的,这时候你完全不需要手动去找这些dll文件,只需要使用…

  • executescalar mysql_ExecuteScalar

    executescalar mysql_ExecuteScalar这两个答案和一点点思考使我想到了一个接近答案的东西。首先再澄清一下:该应用程序是用C#(2.0+)编写的,并使用ADO.NET与SQLServer2005进行通信。镜像设置是托管主体和镜像的两个W2k3服务器以及托管作为监视器的快速实例的第三个服务器。这样做的好处是,故障转移对于使用数据库的应用程序几乎是透明的,它将对某些连接引发错误,但从根本上讲一切都会很好地进行。是的,我们得到了奇怪的误报…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号