Xilium.CefGlue利用XHR实现Js调用c#方法

防外链javascript

博客园原文地址在这里http://www.cnblogs.com/shen6041/p/3442499.htmlhtml

java

Xilium CefGlue是个不错的cef扩展工程,托管地址在这里 https://bitbucket.org/xilium/xilium.cefglue/wiki/Homeweb

固然它还有不少工做要作,这里介绍一下怎样利用XHR实现Js调用c#方法。代码已经在官方Demo里,只是没有中文资料,英文资料也几乎没有,这里只是把它挖出来说一下,本人毫无技术含量。ps:感谢热心的@dmitry.azaraev邮件耐心回复。chrome

本文参考自 http://www.wuleba.com/23614.html,感谢@flydoos给我不少启发。json

另外园子里也有介绍入门教程:http://www.cnblogs.com/liulun/archive/2013/03/18/2874276.html,建议先阅读该系列教程。c#

什么是XHR跨域

XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPSrequests to a web server and load the server response data back into the script.[1] Development versions of all major browsers support URI schemes beyond http: and https:, in particular, blob: URLs are supported.[2]数组

在这里,XHR能够向CefGlue浏览器发送请求,并接收回复,简单的字符串便可经过Post传递,若是是复杂对象,可使用Json转换后传递。浏览器

CefGlue提供的API

RegisterSchemeHandlerFactory(string schemeName, string domainName, CefSchemeHandlerFactory factory)

该方法位于CefRuntime,在启动Initialize后使用。其向浏览器注册一个Scheme处理工厂。

三个参数:

schemeName:scheme名;

domainName:使用域 的名称,这一个参数比较重要,在js中咱们须要向这个地址发送Post请求,能够随便填,好比 "testdomain",那么在js中请求的地址是 "http://testdomain/";

factory:处理工厂,须要来装配一个处理handle。

C#端须要作的两项工做

1.新建一个类DumpRequestResourceHandler,继承自CefResourceHandler,有六个函数须要咱们继承,这里只用到前面三个。

protected override bool ProcessRequest(CefRequest request, CefCallback callback)
        {
            //
            return true;
        }

        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            //
            responseLength = -1;
            redirectUrl = null;
        }

        protected override bool ReadResponse(Stream response, int bytesToRead, out int bytesRead, CefCallback callback)
        {
            //
            bytesRead = 0;
            return false;
               
        }

        protected override bool CanGetCookie(CefCookie cookie)
        {
            return false;
        }

        protected override bool CanSetCookie(CefCookie cookie)
        {
            return false;
        }

        protected override void Cancel()
        {
        }
View Code

2.新建一个类DemoAppSchemeHandlerFactory,继承自CefSchemeHandlerFactory
这个就是咱们须要在注册时用到的工厂,继承他的Creat函数,返回咱们上面建的DumpRequestResourceHandler实例便可。

        protected override CefResourceHandler Create(CefBrowser browser, CefFrame frame, string schemeName, CefRequest request)
        {
            return new DumpRequestResourceHandler();
        }
View Code

Js端须要作的工做
js端须要作的就是建立一个XmlHttpRequest,向以前注册的地址发请求便可,代码在园子里不少,随便搜搜就能找到。

<script type="text/javascript">
        function CreateXmlHttpRequest() {
            var xmlHttp = null;
            if (window.XMLHttpRequest) {
                // For Mozilla, Safari, ...
                xmlHttp = new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                // For Internet Explorer
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xmlHttp;
        }
        function testPost() {
            var xmlHttp = CreateXmlHttpRequest();
            var para = "id=testid&name=testname";
            xmlHttp.open("POST", "http://testdomain/", false);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send(para);
            var result = xmlHttp.status;
            if (xmlHttp.readyState == 4) {
                if (result == 200) {
                    var response = xmlHttp.responseText;
                    alert(response);
                }
            }
        }
    </script>
View Code

这里的js只是举个栗子,你也能够用异步的请求之类的,不要在乎这些细节。

如何接收Post数据

回到DumpRequestResourceHandler 的ProcessRequest方法,post过来的数据就在request.PostData里,GetElements()之后把字节数组转成字符串便可。

怎么返回数据给Js

在DumpRequestResourceHandler的GetResponseHeaders方法里,你须要回复一个接收成功的状态:

response.MimeType = "text/html";
            response.Status = 200;
            response.StatusText = "OK, hello from handler!";
View Code

并写一些头信息:

            var headers = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase);
            headers.Add("Cache-Control", "private");
            headers.Add("Access-Control-Allow-Origin","*");
            response.SetHeaderMap(headers);
View Code

注意这一句代码:headers.Add("Access-Control-Allow-Origin","*"); 由于跨域的问题,若是你的html在本地,XHR的返回永远都是0并无数据。这里是容许全部的跨域访问,存在安全问题暂时不表。

你能够在这里找到更多资料:

http://stackoverflow.com/questions/15977151/loading-local-content-through-xhr-in-a-chrome-packaged-app

http://blog.csdn.net/hfahe/article/details/7730944

在ReadResponse方法里把数据写回去:

response.Write(responseData, pos, bytesToRead);

是否是跑题了?一直都没讲怎么调用c#方法啊?你特么是在逗我吗?
......

我是这样作的,在js的post数据里带参数,好比我要调用的c#方法是A类中的test(string msg);

个人post参数这样传:

var para = "method=test&msg=testtext";

ProcessRequest拿到参数之后就知道了函数的名字和参数,将A类中的test方法反射出来执行,如须要返回值,参考上面的方法便可。

这样作存在一些问题,好比函数没法重载、js和c#类型转换之类的。

我这边项目用到的基本公开给js的函数都很明确,没有重载;另外有复杂对象,也能用json来解决。暂时绕开了这些问题,固然也不是很难解决。

官方的代码实例能够在这里找到:

Xilium.CefGlue.Demo.DemoApp  78行,注册scheme

Xilium.CefGlue.Demo的SchemeHandler文件夹下的DemoAppSchemeHandlerFactory、DumpRequestResourceHandler两个类。

若是有不明白的地方,能够慢慢看代码。

 

感兴趣的,能够加入:WebKit/Blink 内核浏览器开发 QQ交流群:244840771

相关文章
相关标签/搜索