在谷歌浏览器中点击设置,地址栏里出现的不是普通网址,而是chrome://settings/
这个地址就是谷歌浏览器的自定义scheme,cef也提供了自定义协议手段。主要是通过
以下几步:
1.继承一个工厂类MySchemeHandlerFactory : public CefSchemeHandlerFactory
需要包含#include "include/cef_scheme.h"
class MySchemeHandlerFactory : publicCefSchemeHandlerFactory
{public:virtual CefRefPtr Create(CefRefPtrbrowser,
CefRefPtrframe,const CefString&scheme_name,
CefRefPtrrequest)
OVERRIDE {//Return a new resource handler instance to handle the request.
return newMyResourceHandler();
}private:
IMPLEMENT_REFCOUNTING(MySchemeHandlerFactory);
};
2.继承一个资源类class MyResourceHandler : public CefResourceHandler
class MyResourceHandler : publicCefResourceHandler
{public:
MyResourceHandler() {}virtual bool ProcessRequest(CefRefPtrrequest,
CefRefPtrcallback)
OVERRIDE {
std::string url = request->GetURL();
//if (strstr(url.c_str(), "handler.html") !=NULL)
data_= "hello cef";//返回到页面中的内容
callback->Continue();//这个一定要有
return true;//}virtual void GetResponseHeaders(CefRefPtrresponse,
int64&response_length,
CefString&redirectUrl) OVERRIDE {
response->SetMimeType("text/html");
response->SetStatus(200);
response_length=data_.length() ;
}virtual voidCancel() OVERRIDE {//Cancel the response...
}virtual bool ReadResponse(void*data_out,intbytes_to_read,int&bytes_read,
CefRefPtrcallback)
OVERRIDE {int size =static_cast(data_.length());
memcpy(data_out, data_.c_str(), size);
bytes_read=size;return true;
}private:
std::stringdata_;
IMPLEMENT_REFCOUNTING(MyResourceHandler);
};
3.在初始化cef那几行代码后面增加一句
CefRegisterSchemeHandlerFactory("sin", "test", new MySchemeHandlerFactory());
CefSettings settings;
CefSettingsTraits::init(&settings);
settings.multi_threaded_message_loop= true;
CefRefPtr app(newSimpleApp); CefInitialize(main_args, settings, app.get(), sandbox_info);//自定义scheme
CefRegisterSchemeHandlerFactory("sin", "test", new MySchemeHandlerFactory());
4.我看有的教程里写的还要在自定义的CefApp类中修改OnRegisterCustomSchemes函数,增加
registrar->AddCustomScheme("sin", true, false, false, false, true, false);
但是我添加还是不添加都没有问题,都可以出来。
5.这时,运行程序,在地址栏输入sin://test之后就会显示页面,内容是hello cef
6.在第2步中,如果不注释if语句if (strstr(url.c_str(), "handler.html") != NULL)
那么,就需要输入sin://test/handler.html才能显示内容hello cef
原文:https://www.cnblogs.com/sinceret/p/10417941.html