本章主要講解自定義javascript函數進行本地調用和自定義本地域名。
1、自定義javascript函數
1)得到browser對象然後註冊自己的js對象。如下:
//註冊usbjs對象
browser.RegisterJsObject("usbKey", new UsbKeyBound());
//注意在js函數裏面只駝峯寫法開頭,如果要使用C#寫法就使用下面的註冊方式。
//BindingOptions bo = new BindingOptions();
//bo.CamelCaseJavascriptNames = false;
//browser.RegisterJsObject("usbKey", new UsbKeyBound(), bo);
2) usbkey就是js對象的名字,下面我們來看看UsbKeyBound中的內容。
public class UsbKeyBound
{
public void ShowTest()
{
MessageBox.Show("這個一個測試");
}
}
3)下面來看看在html中怎麼調用自定義的js方法。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<button type="button" onclick="test()">點擊這裏</button>
</body>
</html>
<script type="text/javascript">
function test() {
//注意在js函數裏面只認小寫開頭
usbKey.showTest();
}
</script>
效果如下圖:
4)自定義js函數還有一種異步註冊js方式和帶參數的調用方式,具體的方法請問度娘啦。
大家在圖片中看到這樣的域名訪問custom://cefsharp/zpy.html,都想知道怎麼怎麼自己註冊的,下面我們來看看怎麼註冊自定義域名,並且訪問本地html文件。
註冊本地html文件
在settings中這行代碼註冊了Scheme:
settings.RegisterScheme(new CefCustomScheme
{
//CefSharpSchemeHandlerFactory.SchemeName的值是"custom"
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(),
IsSecure = true //treated with the same security rules as those applied to "https" URLs
});
來看看CefSharpSchemeHandlerFactory
以下是註冊本地的html文件的,這樣就可以通過自定義的url訪問本地文件。
static CefSharpSchemeHandlerFactory()
{
ResourceDictionary = new Dictionary<string, string>
{
{ "/home.html", Resources.home_html },
{ "/assets/css/shCore.css", Resources.assets_css_shCore_css },
{ "/assets/css/shCoreDefault.css", Resources.assets_css_shCoreDefault_css },
{ "/assets/css/docs.css", Resources.assets_css_docs_css },
{ "/assets/js/application.js", Resources.assets_js_application_js },
{ "/assets/js/jquery.js", Resources.assets_js_jquery_js },
{ "/assets/js/shBrushCSharp.js", Resources.assets_js_shBrushCSharp_js },
{ "/assets/js/shBrushJScript.js", Resources.assets_js_shBrushJScript_js },
{ "/assets/js/shCore.js", Resources.assets_js_shCore_js },
{ "/bootstrap/bootstrap-theme.min.css", Resources.bootstrap_theme_min_css },
{ "/bootstrap/bootstrap.min.css", Resources.bootstrap_min_css },
{ "/bootstrap/bootstrap.min.js", Resources.bootstrap_min_js },
{ "/BindingTest.html", Resources.BindingTest },
{ "/ExceptionTest.html", Resources.ExceptionTest },
{ "/PopupTest.html", Resources.PopupTest },
{ "/SchemeTest.html", Resources.SchemeTest },
{ "/TooltipTest.html", Resources.TooltipTest },
{ "/FramedWebGLTest.html", Resources.FramedWebGLTest },
{ "/MultiBindingTest.html", Resources.MultiBindingTest },
{ "/ScriptedMethodsTest.html", Resources.ScriptedMethodsTest },
{ "/ResponseFilterTest.html", Resources.ResponseFilterTest },
{ "/DraggableRegionTest.html", Resources.DraggableRegionTest },
{ "/CssAnimationTest.html", Resources.CssAnimation },
{ "/CdmSupportTest.html", Resources.CdmSupportTest },
{ "/Recaptcha.html", Resources.Recaptcha },
{ "/zpy.html", Resources.zpy }
};
}
以下是資源文件所在目錄: