如果有人需要一个例子,这是我做到的一种方式:
确定您希望使用的自定义“协议”
这是一个作为宏字符串的示例
#define PROTO_MYAPPCOMMAND "myapp://"
在您的自定义 CefApp 类(继承自 CefApp 的类)上,
也继承自 CefRenderProcessHandler。
-
实现 OnBeforeNavigation() 函数:
//declare (i.e. in header)
virtual bool OnBeforeNavigation(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request,
NavigationType navigation_type, bool is_redirect) OVERRIDE;
//implementation
bool CClientApp::OnBeforeNavigation(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request,
NavigationType navigation_type, bool is_redirect)
{
CefString cefval = request->GetURL();
CString csval = cefval.c_str();
if (csval.Find(PROTO_MYAPPCOMMAND, 0) == 0)
{
//process the command here
//this is a command and not really intended for navigation
return true;
}
return false; //true cancels navigation, false allows it
}
以下是添加“退出”应用按钮的示例:
在cpp中
#define STR_COMMANDAPPEXIT _T("command.appexit")
bool CClientApp::OnBeforeNavigation(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, NavigationType navigation_type, bool is_redirect)
{
CefString cefval = request->GetURL();
CString csval = cefval.c_str();
if (csval.Find(PROTO_MYAPPCOMMAND, 0) == 0)
{
CString command = url;
command.Replace(PROTO_MYAPPCOMMAND, _T(""));
if (command.Find(STR_COMMANDAPPEXIT, 0) == 0)
{
::PostMessage(hwnd, WM_CLOSE, NULL, NULL);
}
//this is a command and not really intended for navigation
return true;
}
return false; //true cancels navigation, false allows it
}
还为所有操作创建了一个 js 实用程序文件以简化调用它们
var MYHOST = MYHOST || {};
/// Exit the Application (host app)
MYHOST.ExitApp = function() {
window.location = 'myapp://command.appexit';
};
在页面js中(即在按钮/div点击中)
<div class="exitbutton" onclick="MYHOST.ExitApp();">Exit</div>
如果需要传入参数,只需在js中的url中追加并解析即可
cpp 中的字符串,如下所示:
MYHOST.DoSomething = function() {
window.location = 'myapp://command.dosomething?param1=' + value1 + "¶m2=" + value2 + "¶m3=" + value3;
};
注意:我已经简化了代码,但请添加验证等
希望这会有所帮助!